通过Hosting Rewrites在Firebase GCP Functions中读取Cookie失败问题
问题场景
用Firebase Hosting把所有流量rewrite到云函数,但通过Hosting域名访问时,函数里死活拿不到请求Cookie——req.cookies是空的,req.headers.cookie直接是undefined,但是直接访问云函数的URL就一切正常。
你的代码和配置
云函数代码:
const { runWith } = require('firebase-functions'); const cookieParser = require('cookie-parser'); const express = require('express'); const app = express(); app.use(cookieParser()); function handleRequest(req, res) { res.cookie('firebase1', 'test', {}); if (process.env.HOSTNAME) { res.cookie('firebase2', 'test', { domain: process.env.HOSTNAME, }); } res.cookie('firebase3', 'test', { domain: req.hostname, }); return res.json({ hostname: process.env.HOSTNAME, 'req.cookies': req.cookies, // always empty 'req.headers.cookie': req.headers.cookie, // always undefined }); } app.get('*', handleRequest); app.use(handleRequest); exports.index = runWith({ timeoutSeconds: 10, memory: '128MB', }).https.onRequest(app);
firebase.json配置:
{ "functions": { "ignore": [ "node_modules", ".git", "firebase-debug.log", "firebase-debug.*.log" ] }, "hosting": { "public": "public", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "**", "function": "index" } ] } }
问题原因
Firebase Hosting默认不会把请求中的Cookie转发给云函数,这是它的默认缓存和安全策略——毕竟Hosting本来是给静态资源用的,动态请求头默认会被过滤掉,得手动配置让它放行Cookie。
解决步骤
1. 修改firebase.json,允许Cookie转发
在rewrites规则里加个headers配置,指定把请求的Cookie传递给函数,同时关掉缓存避免干扰:
{ "functions": { "ignore": [ "node_modules", ".git", "firebase-debug.log", "firebase-debug.*.log" ] }, "hosting": { "public": "public", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "**", "function": "index", "headers": { "Cache-Control": "no-cache", "Cookie": "$requestCookie" } } ] } }
2. 调整Cookie的设置参数
设置Cookie的时候,要确保domain和当前请求的域名一致,同时加上path: '/'保证全站都能拿到,还可以加httpOnly提升安全性:
function handleRequest(req, res) { const currentDomain = req.hostname; // 统一Cookie配置 const cookieOptions = { domain: currentDomain, path: '/', httpOnly: true // 可选,防止前端JS读取,更安全 }; res.cookie('firebase1', 'test', cookieOptions); if (process.env.HOSTNAME) { res.cookie('firebase2', 'test', { ...cookieOptions, domain: process.env.HOSTNAME }); } res.cookie('firebase3', 'test', cookieOptions); return res.json({ hostname: process.env.HOSTNAME, 'req.cookies': req.cookies, 'req.headers.cookie': req.headers.cookie, 'currentDomain': currentDomain }); }
3. 重新部署
跑命令更新你的函数和Hosting配置:
firebase deploy --only functions,hosting
部署完再用Hosting域名访问,就能正常读取Cookie了。
内容的提问来源于stack exchange,提问作者d-_-b
相关产品推荐
相关产品推荐

