You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Firebase第二代HTTPS可调用函数的响应设置缓存头?

为Firebase第二代HTTPS可调用函数设置缓存头

可以为第二代HTTPS可调用函数设置Cache-Control等响应头,无需切换到onRequest。在v2版本的onCall函数中,你可以通过event.res对象直接操作响应头,同时保留onCall自带的用户认证、请求格式校验等特性。

修改你的函数模板,添加缓存头设置逻辑:

import { getErrorMessage } from "@repo/common";
import { logger } from "firebase-functions";
import { z } from "zod";
import { region } from "~/config.js";
import { onCall, HttpsError } from "firebase-functions/v2/https";

const schema = z.object({
  something: z.string(),
});

export const my_callable_function = onCall(
  {
    region,
  },
  async (event) => {
    try {
      const { something } = schema.parse(event.data);

      console.log(`Do something: ${something}`);

      // 设置Cache-Control缓存头,示例为缓存1小时
      event.res.set('Cache-Control', 'public, max-age=3600');

      // 返回你的业务数据
      return { result: "your data here" };
    } catch (err) {
      const message = getErrorMessage(err);
      logger.error(`Failed to get something: ${message}`);

      throw new HttpsError("internal", message, err);
    }
  }
);

注意事项:

  • 根据响应内容调整缓存策略:如果返回的是用户专属数据,将public改为private,避免不同用户间的缓存共享;
  • max-age的值以秒为单位,根据你的需求调整缓存时长;
  • 确保缓存头设置在返回结果之前执行,否则不会生效。

内容的提问来源于stack exchange,提问作者Thijs Koerselman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 01:26:00