Reputation: 23171
I'm using Firebase Functions, and Firebase Hosting. Hosting redirects all traffic to my function.
Request cookies are not available when requesting the Hosted site (i.e. not the cloud function URL). Is there no way to access request cookies?
I'm migrating a website to Firebase and was assuming I could follow basic web principals of having access to same-domain cookies.
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"
}
]
}
}
Upvotes: 1
Views: 788
Reputation: 23171
Answer from Firebase's support team:
When using Firebase Hosting together with Cloud Functions or Cloud Run, cookies are generally stripped from incoming requests. This is necessary to allow for efficient CDN cache behavior. Only the specially-named __session cookie is permitted to pass through to the execution of your app.
When present, the __session cookie is automatically made a part of the cache key, meaning that it's impossible for two users with different cookies to receive the other's cached response. Only use the __session cookie if your app serves different content depending on user authorization. Also, you need to set the Cache-Control Header as private res.setHeader('Cache-Control', 'private').
Upvotes: 2
Reputation: 83103
I haven't tested it but the Express API doc indicates that, since you use the cookie-parser
middleware, you should do req.cookies
and not req.headers.cookie
Upvotes: 0