Firebase Hosting is not compatible with Express session

After setting up my code as shown below, I noticed that sessions are being persisted and the page is able to count the number of visits.

app.set('trust proxy', true)
// The documentation specifies '1' instead of 'true'

app.use(session({
   secret: 'my secret',
   proxy: true,
   resave: false,
   saveUninitialized: true,
   cookie: { secure: false }
}))

app.listen(3000, function(){
   console.log("Server is connected!");
});

app.get("/login", (req, res) => {
   if(req.session.page_views){
       req.session.page_views++;
       res.send("You visited this page " + req.session.page_views + " times");
   } else {
       req.session.page_views = 1;
       res.send("Welcome to this page for the first time!");
   }
});

However, when I removed the app.listen(3000, ...) and opted to run on localhost by executing firebase serve in the CLI, the sessions were no longer persisted.

I also attempted deploying to a production environment using firebase deploy, but unfortunately, the sessions were still not persisted.

I have made several adjustments within the app.use(session({ section and I believe the solution lies within those changes.

Any suggestions?

UPDATE

const express = require('express');
const session = require('express-session');
const FirestoreStore = require('firestore-store')(session);
const bodyParser = require('body-parser');

app.use(cookieParser('My secret'));
app.use(bodyParser.urlencoded({ extended: true }));

app.use(session({
    store: new FirestoreStore({
         database: firebase.firestore()
    }),
    secret: 'My secret',
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge : 60000,
             secure: false,
             httpOnly: false }
}));

Answer №1

Have you considered using FirebaseStore instead of FirestoreStore for your project?

If you're working with Express, here's a guide on how to integrate FirebaseStore:

Express

Note: In Express 4, make sure to pass express-session to connect-session-firebase function to extend express-session.Store:

const express = require('express');
const session = require('express-session');
const FirebaseStore = require('connect-session-firebase')(session);
const firebase = require('firebase-admin');
const ref = firebase.initializeApp({
  credential: firebase.credential.cert('path/to/serviceAccountCredentials.json'),
  databaseURL: 'https://databaseName.firebaseio.com'
});

express()
  .use(session({
    store: new FirebaseStore({
      database: ref.database()
    }),
    secret: 'keyboard cat',
    resave: true,
    saveUninitialized: true
  }));

Remember that considering the security provided by this dependency is crucial:

Make sure to set proper rules if you are using a publicly available Firebase Database:

{
  "rules": {
    ".read": "false",
    ".write": "false",
    "sessions": {
      ".read": "false",
      ".write": "false"
    },
    "some_public_data": {
      ".read": "true",
      ".write": "auth !== null"
    }
  }
}

For further information on Firebase rules and connect-session-firebase, check out Firebase rules and connect-session-firebase

Answer №2

If you're utilizing firebase hosting, it's a good idea to utilize a connector that links your express session with firebase.

You may want to experiment with the connect-session-firebase middleware, which seamlessly integrates the firebase database store with your current express session. This could potentially resolve any issues related to session persistence.

UPDATE:

In case you are using firebase hosting along with cloud functions, keep in mind that only a cookie named __session can be set. Therefore, you will need to use this specific name for persisting sessions in firebase hosting.

app.use(session({
    store: new FirestoreStore({
         database: firebase.firestore()
    }),
    name: '__session',
    secret: 'My secret',
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge : 60000,
             secure: false,
             httpOnly: false }
}));

For more information:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for the absence of this Javascript function in my attribute?

I have been working on an app using electron, and I have a function that successfully adds tabs to the app. The issue arises when I try to add tabs via JavaScript with the onclick attribute - they show up as expected but do not execute the code to hide and ...

The database server is not appearing on the main.js page of the client

My client's main.js file contains code that is meant to display previous form entries on the webpage, but after submitting the form, no entries appear on the HTML page. My server is running on port 7777 and the root route works in Postman, as does the ...

React beautiful dnd and Material UI list encountering compatibility problem

I recently encountered an issue while using react beautiful dnd to create a rearrangeable Material UI List. Everything was working correctly, except for the ListItemSecondaryAction within the list. When dragging a list item, the ListItemText and ListItemIc ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

Injecting CSS styles into a webpage using a Chrome extension before the page has completely loaded to achieve instant customization

As a newcomer to creating Chrome (or other browser) extensions, I am working on developing one that applies custom CSS rules to specific page elements. Overall, it seems to be functioning as intended, but with some minor issues. One issue I have encounter ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

If a specific class is identified, add a border to the div when clicked using JavaScript

Is there a way to use javascript/jquery to add a border to a selected div? I have multiple rows with columns, and I want only one column per row to be highlighted with a border when clicked. Each row should have one column with a border, so it's clear ...

After retrieving a value from attr(), the object does not have the 'split' method available

I need to implement the split method on a variable fetched using attr. This is the code snippet I am attempting: $(document).ready(function() { $('.some_divs').each(function() { var id = $(this).attr('id'); var ida = ...

Setting the height of columns in a Bootstrap panel to 100%

Is there a way to achieve 100% height for all three columns even without content? Check out this JSFiddle: <div class="row"> <div class="col-md-12"> <div class="shadow panel panel-default"> <div class="blue white-bord ...

The concept of nested ng-repeat in AngularJS

My HTML structure is as follows: <div class="fields-plan"data-ng-repeat="roomname in assign.roomname"> <section> <span>Room: {{roomname}}</span> </section> <ul data-ng-repeat="r ...

The backface remains visible despite being designated as "hidden"

I have successfully created a "flip card" in CSS3, where the card flips downward to reveal the other side when a user hovers over it. I have ensured that the back face is not visible by setting backface-visibility to hidden. However, despite my efforts, th ...

Oops! You forgot to include the necessary getStaticPaths function for dynamic SSG pages on '/blogs/[post]'

Whenever I attempt to execute npm run build, an error occurs. The following build error occurred: Error: getStaticPaths is required for dynamic SSG pages and is missing for '/blogs/[post]'. This is the code snippet causing the issue: function ...

Exploring the process of querying two tables simultaneously in MySQL using PHP

I currently have a search box in my PHP file that only searches from the "countries" table. However, I also have another table called "continent" and I would like the search box to retrieve results from both the "countries" and "continent" tables. Here is ...

I am experiencing difficulty with the function from flip.to not functioning properly on my Next.js project

I was given this script by flip.to <script> !function(b,e){ (b[e] = b[e] || []).push({ flipto: { bookingEngine: "Demo", companyCode: "XX", code: "YYYY", ...

Having difficulty in sending emails through Nodemailer using a Google App Password

I implemented a route in an API that involves sending an email to users upon signing up. Utilizing nodemailer and a Google App password, everything was running smoothly until February 3rd, 2023 when the connection suddenly ceased without any changes to the ...

Issue with using variables in nodejs, express, and EJS: Undefined

Having some trouble with EJS here. I am using response.render('agent.html', {name: 'aaaa'});, and in my HTML script, I attempt to access <%= this.name %>. Unfortunately, I keep getting a ReferenceError: aaaa is not defined. Any sugge ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

Ways to showcase INPUT TYPE when making a Selection?

I've been struggling with a simple issue and despite trying multiple solutions, I can't seem to get it right. I have a form where I'm using the <select> tag with two options: coo and uh. What I want is for an additional input type fiel ...

In search of a hover functionality similar to what can be found on Stack Overflow

I am really impressed by the hover effects on StackOverflow. I would love to incorporate a similar feature into my own web application. Can anyone provide me with more information? What is this feature called? Are there any libraries available for it? I h ...

I am encountering an issue with the react-use-cart package as it requires the string "id" while my API data only provides the object "_id". Is there a way to convert or manipulate the

Seeking assistance with integrating an item into a cart system. The function requires the id of the item, but my item only generates the _id and not simply the id. Grateful for any insights from those with expertise in this area. Thank you in advance! htt ...