Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase cloud function won't store cookie named other than "__session"

i followed the sample of authorized-https-endpoint and only added console.log to print the req.cookies, the problem is the cookies are always empty {} I set the cookies using client JS calls and they do save but from some reason, I can't get them on the server side.

here is the full code of index.js, it's exactly the same as the sample:

'use strict';  const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); const express = require('express'); const cookieParser = require('cookie-parser')(); const cors = require('cors')({origin: true}); const app = express();  const validateFirebaseIdToken = (req, res, next) => {   console.log(req.cookies); //// <----- issue this is empty {} why??    next(); };  app.use(cors); app.use(cookieParser); app.use(validateFirebaseIdToken); app.get('/hello', (req, res) => {   res.send(`Hello!!`); });  exports.app = functions.https.onRequest(app); 

store cookie:

curl http://FUNCTION_URL/hello --cookie "__session=bar" // req.cookies = {__session: bar}

doesn't store:

curl http://FUNCTION_URL/hello --cookie "foo=bar" // req.cookies = {}

like image 992
Sagiv Ofek Avatar asked Jul 05 '17 14:07

Sagiv Ofek


2 Answers

If you are using Firebase Hosting + Cloud Functions, __session is the only cookie you can store, by design. This is necessary for us to be able to efficiently cache content on the CDN -- we strip all cookies from the request other than __session. This should be documented but doesn't appear to be (oops!). We'll update documentation to reflect this limitation.

Also, you need to set Cache-Control Header as private

res.setHeader('Cache-Control', 'private'); 
like image 68
Michael Bleigh Avatar answered Oct 04 '22 16:10

Michael Bleigh


Wow this cost me 2 days of debugging. It is documented (under Hosting > Serve dynamic content and host microservices > Manage cache behavior, but not in a place that I found to be useful -- it is at the very bottom "Using Cookies"). The sample code on Manage Session Cookies they provide uses the cookie name session instead of __session which, in my case, is what caused this problem for me.

Not sure if this is specific to Express.js served via cloud functions only, but that was my use case. The most frustrating part was that when testing locally using firebase serve caching doesn't factor in so it worked just fine.

like image 45
ehed Avatar answered Oct 04 '22 16:10

ehed