skip to Main Content

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"
      }
    ]
  }
}

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    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').


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search