Unable to access the 'session' property because it is undefined - Administration of Session Cookie in Firebase Authentication-generated cookie

I'm encountering an issue where, even after setting a Firebase session cookie, I face difficulty accessing it in a secure endpoint due to the fact that req doesn't retrieve the cookie.

Following the instructions outlined in a Firebase tutorial titled Manage Session Cookies, I'm trying to create a cookie after a user logs in using the

Firebase signInWithEmailAndPassword
function. The idToken of the user is then passed to a POST request:

Initially, I create a token and send it to an endpoint:

function signIn() {
  var email = document.getElementById('email').value;
  var password = document.getElementById('password').value;

  firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === 'auth/wrong-password') {
        alert('Wrong password.');
    } else {
        alert(errorMessage);
    }

    document.getElementById('quickstart-sign-in').disabled = false;

  }).then(user => {
    // Retrieving the user's ID token as it is required to retrieve a session cookie.
    return user.getIdToken().then(idToken => {
      if (firebase.auth().currentUser) {
        $.ajax({
          method: 'POST',
          url: '/login',
          data: {'email':firebase.auth().currentUser.email,idToken},
          success: function(data) {
            //perform other tasks...
          }
        });          
      }      
    });
  })
}

The URL endpoint retrieves the idToken from the previous POST request, generates a session cookie using createSessionCookie, and then sets the cookie with

res.cookie('session', sessionCookie, options)
:

exports.postLogin = (req, res, next) => {

  // Retrieving the passed ID token
  const idToken = req.body.idToken.toString();

  // Setting session expiration to 14 days.
  const expiresIn = 60 * 60 * 24 * 14 * 1000;

  var exampleDB = admin.database().ref('exampleDB');
  exampleDB.once('value', function(snapshot) {
    //performing unrelated actions...
    //generating random data...
  }).then(function() {
    admin.auth().createSessionCookie(idToken, {expiresIn})
      .then((sessionCookie) => {
       // Setting cookie policy for session cookie.
       const options = {maxAge: expiresIn, httpOnly: true, secure: true};
       res.cookie('session', sessionCookie, options);
       res.status(200).send(randomData).end();
      }, error => {
       res.status(401).send('UNAUTHORIZED REQUEST!');
      });    
  });
};

The issue arises when I navigate to another endpoint, /dashboard. The cookie that I set cannot be located, resulting in an error message indicating

TypeError: Cannot read property 'session' of undefined
for my session cookie:

exports.dashboard = (req, res, next) => {
  const sessionCookie = req.cookies.session || '';
  // a bunch of other code surrounding the session cookie that remains unused due to the absence of req.cookies.session
}

Am I retrieving the cookie incorrectly? Have I not set the cookie correctly? Or is the cookie not being carried over to this new endpoint, /dashboard, from the page where the POST to /login occurs?

Upon logging the req to /dashboard, I observe the following information, but I'm unsure if it's from a different session or source. If it is related to Firebase, I'm unsure of the correct method to access it:

  sessionID: 'ublahxARQVljyGRblahPQrei',
  session: 
   Session {
     cookie: 
      { path: '/',
        _expires: null,
        originalMaxAge: null,
        httpOnly: true },
     returnTo: '/dashboard',
     flash: {},
     _csrfSecret: 'r46blahE+kOzblah5==' },

Answer №1

It is important to utilize the __session cookie for your needs.

When Firebase Hosting is used in conjunction with Cloud Functions or Cloud Run, incoming requests often lack cookies. source

A similar issue has been addressed in a different context here: Firebase Functions : How to store simple cookies to remember an authenticated user

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

Determine whether a click event originated from within a child window

Currently, I am utilizing window.open to initiate a new window in javascript and my goal is to identify clicks made within the child window. Essentially, if a click event occurs in the child window, I aim to modify the parent window accordingly. I have a ...

Exploring disparities between the Client SDK and Admin SDK in conducting firestore queries

I am encountering difficulties with my query while running it in Firebase Functions. It functions perfectly on the client side, but fails to work in Functions. I am curious if there is a way to modify it to function with Admin SDK as well. Am I making any ...

Using React and graphql to show information on selected options across components

Currently, I'm facing a challenge in determining my next step. In productList.js, there is a straightforward select dropdown class component that displays all data from Products (id, name, brand,vintage) using graphql(apollo). It successfully sho ...

Tips for creating an onChange function in an input field using jQuery

I am looking to dynamically create inputs where each input has an `onChange` function with a variable. Here is my code: var distinct_inputs = 0; $('.icon1').click( function(){ distinct_inputs = distinct_inputs + 1 ; $('#insert-file&apo ...

Using Jquery to extract URL parameters

Can anyone suggest a jQuery function I can use to fetch URL parameters? I've been utilizing the following function, which works well; however, it encounters issues when the URL doesn't have any parameters. I would like it to return an empty stri ...

Utilizing an API endpoint within a POST request

I'm facing a bit of a roadblock here and struggling to figure out the best approach. I need to add a new video to my database, gathering most information from a view form but needing some keys from an API. Here's a simplified version of what I ha ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Retrieve data from a local JSON file and showcase it in a list within a Next.js project. The error "Property 'data' does not exist on type String

Having trouble displaying the names of crates (which are filled with records/albums) from a local JSON file. The names aren't showing up and I'm wondering if I should be using params or if perhaps not stringifying the JSON would help. Visual Stud ...

Navigating with React Router and Express

As a Meteor user, I am curious about the distinction between Express and React Router Dom. In my experience with Meteor, I would typically render a component that included the browser router and routes. However, I find myself puzzled by the use of Expres ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

What is the best way to import an external file from the project's root directory using webpack?

I am currently working on a unique npm package that will allow for the integration of custom rules from the project root. This functionality is similar to how prettier searches for a .prettierrc file in the project root. For this particular package, I am ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...

The jQuery .load function does not function properly when an ajax query is already underway

My web application utilizes dynamic loading of content within the same div (.content) through either an ajax request or a .load() request. An example of the ajax request code snippet is: $(document).on('click', '.button1', functio ...

Generating a JavaScript array using concealed data

var a1=$("#orderprogress").val().toFixed(2);//a1=50 var a2=$("#poprogress").val().toFixed(2); //a2=70 If I were to create an array in this format, how should I proceed? graphData = new Array( [a1 value,'#222222'],//[50,'#22222 ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

Troubleshooting Bootstrap bug caused by rollupPluginBabelHelpers

I am currently working on a Bootstrap 4 website. I noticed that in Internet Explorer, the modal works fine when opened for the first time, but then displays an error in the console and does not open when trying to do so a second time on the same window. On ...

Ensure your mobile device is age 13 or over before proceeding

I am developing a project with Next js. Here, I want to render a component if it is a mobile device. However, if I use the isMobileDevice value in jsx, I get the errors below. import useTranslation from "next-translate/useTranslation"; import isM ...

Update a document by removing elements from an array where the objects are of a certain value

I am trying to remove specific tweet objects from the timeline list within the user model. The tweets I want to remove are those authored by a user with a matching id user._id. I attempted the following approach: router.get("/follow/:userId", is ...

Tips for setting up Highcharts tooltip.headerFormat using the function getDate() plus 5

I'm facing a little challenge trying to understand how the JavaScript function getDate interacts with Highcharts datetime on xAxis. My goal is to show two dates in the tooltip header, forming a date range like this: 1960/1/1 - 1965/1/1. The first da ...