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

如何配置Firebase Hosting模拟器遵循Cloud Function的Cache-Control头

如何配置Firebase Hosting模拟器以遵循Cloud Function返回的Cache-Control头?

问题背景

我设置了Cloud Function返回带有Cache-Control头的响应,但通过Firebase Hosting模拟器访问时,尽管响应头正确返回,每次请求仍会触发函数执行,没有按照缓存规则复用响应内容。

函数代码(Python)

from firebase_functions import https_fn
from firebase_admin import initialize_app

initialize_app()

HTTPS_CACHING_HEADER = {'Cache-Control': 'public, max-age=300, s-maxage=300'}


@https_fn.on_request(region='europe-north1')
def foo(req: https_fn.Request) -> https_fn.Response:
  print("**function was executed**")
  return https_fn.Response(headers=HTTPS_CACHING_HEADER, response="some content")

当前firebase.json配置

{
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "venv",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ]
    }
  ],
  "emulators": {
    "functions": {
      "port": 5001
    },
    "hosting": {
      "port": 8888
    },
    "ui": {
      "enabled": true
    },
    "singleProjectMode": true
  },
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/foo",
        "function": {
          "functionId": "foo",
          "region": "europe-north1",
          "pinTag": true
        }
      }
    ]
  }
}

问题现象

  • 多次执行curl http://127.0.0.1:8888/foo,响应中正确返回Cache-Control: public, max-age=300, s-maxage=300头
  • 但每次请求都会触发函数执行,日志重复输出**function was executed**,未从缓存返回内容

解决方案

Firebase Hosting模拟器默认不会自动缓存重定向到Cloud Function的响应,需要通过配置明确开启缓存支持:

1. 更新firebase.json的Hosting配置

在hosting节点下添加headers规则,为目标路径指定缓存策略(可与函数返回的头保持一致,避免冲突):

"hosting": {
  "public": "public",
  "ignore": [
    "firebase.json",
    "**/.*",
    "**/node_modules/**"
  ],
  "headers": [
    {
      "source": "/foo",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "public, max-age=300, s-maxage=300"
        }
      ]
    }
  ],
  "rewrites": [
    {
      "source": "/foo",
      "function": {
        "functionId": "foo",
        "region": "europe-north1",
        "pinTag": true
      }
    }
  ]
}

2. 确保模拟器缓存启用

默认情况下模拟器缓存是开启的,启动模拟器时使用标准命令即可:

firebase emulators:start

如果之前启动时添加了--no-cache参数,需要移除该参数。

3. 正确测试缓存行为

测试时避免使用带强制刷新的curl参数,使用标准请求:

curl -v http://127.0.0.1:8888/foo

第一次请求会触发函数执行,后续在max-age有效期内的请求应该直接返回缓存内容,不会再调用函数。


额外注意事项

  • 模拟器的缓存行为与生产环境略有差异:生产环境中s-maxage会被CDN层使用,模拟器主要遵循max-age规则
  • 重启模拟器后缓存会被清空,需要重新发起第一次请求填充缓存
  • 若配置后仍不生效,检查Firebase CLI版本是否为最新(执行firebase --version),旧版本可能存在缓存逻辑问题,可通过npm install -g firebase-tools更新
  • 确保函数返回的Cache-Control头与Hosting配置中的值一致,避免冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:27:12