Is it feasible to maintain a persistent login session in Firebase without utilizing the firebase-admin package through the use of session cookies?

Currently, I am integrating Firebase into my next.js application for user login functionality. The issue I am facing is that users are getting logged out every time they switch paths within the site. Even though their session cookie has not expired, if they navigate to a specific path like /question/page, Firebase automatically logs them out. My goal is to ensure that users remain authenticated until their session cookie expires, regardless of which path they visit on the site. Unfortunately, I cannot use the firebase-admin package as it causes crashes in my next.js environment. Therefore, I have to rely on the standard Firebase package along with the js-cookie library.

componentDidMount() {
        let user = firebase_auth.currentUser;
        console.log("User: ", user);

        if (user) {
            this.setState({user_logged_in: true});
            return firebase_auth.currentUser.getIdToken(true).then(function (token) {
                Cookies.set('__session', token, {expires: 7});
            })
        }
        else {
            this.setState({user_logged_in: false})
        }
    }

I need assistance utilizing the session cookie mentioned in the code above to prevent users from being constantly logged out when navigating between different paths. Any guidance or suggestions would be greatly appreciated!

Thank you in advance for your help!

Answer №1

The Firebase Authentication SDKs are designed to seamlessly maintain the user state even when the page or app is reloaded, ensuring that the user's authentication status is preserved upon restart.

If you are experiencing issues with accessing firebase.auth().currentUser, it is likely due to Firebase continuously verifying the validity of the authentication state.

To resolve this issue, consider implementing an auth state listener by following this guide:

componentDidMount() {
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      this.setState({user_logged_in: true});
      firebase_auth.currentUser.getIdToken(true).then(function (token) {
          Cookies.set('__session', token, {expires: 7});
      })
    } else {
      this.setState({user_logged_in: false})
    }
  });
}

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

Ways to solely cache spa.html using networkfirst or ways to set up offline mode with server-side rendering (SSR)

I am facing an issue with my application that has server-side rendering. It seems like the page always displays correctly when there is an internet connection. However, I am unsure how to make Workbox serve spa.html only when there is no network available. ...

Exploring the depths of Next.js and ASP.NET Core Web API with the challenge of DEPTH_ZERO_SELF_SIGNED_CERT

My current setup involves utilizing Asp.net Core Web API as the backend and Next.js as the frontend. The API is running on localhost with a self-signed SSL, making it accessible through https. On the other hand, Next.js runs on localhost without SSL, only ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

Encountering an Issue with NextJS on GAE: EROFS Error indicating a read-only file system

Trying to deploy a customized Next.js application into Google App Engine has hit a snag. The project runs smoothly locally and on Google Cloud Platform CLI, but upon successful deployment using gcloud app deploy, an error arises when opening the app. 2020 ...

How can I delete the onmouseover function in HTML?

Is there a way to remove the (onmouseover="mouseoversound.playclip()") function from the following HTML code? <a href="roster.html" onmouseover="mouseoversound.playclip()">Roster</a> Can we instead implement this functionality in a JavaScript ...

Combining ApolloProvider and StatsigProvider in ReactJs: A Step-by-Step Guide

Currently in my React (Next.js) application, I am utilizing statsig-react to switch between mastergraphql endpoint URLs. However, I am encountering an issue when trying to connect statsig with Apollo. This is how my app.js file looks like: const apollo = ...

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

Tips for displaying multiple results from a MySQL query in a single .ejs file using Node.js and Express

Currently diving into Node.js and working on a web application, I am faced with the challenge of rendering twice in the same .ejs file. Consider the scenario presented in the following .ejs file: <table> <% rows.forEach(function(ind){ %> /* m ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

Adapting designs within an Embedded Frame - JQuery

I am dealing with a dialog type popup that appears when a button is clicked by the user. Inside this popup, there is a form that needs to be submitted in order to change the width and height of the popup using the following code: $(document).ready(functio ...

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

Running the command "npm start" in ghost (node.js) is causing an error

After successfully installing node.js, I attempted to set up Ghost. However, when running the installation for Ghost using npm install --productions I encountered the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

Can I Select a Specific Node in React Component with Unique Behavior Upon Reuse?

Seeking advice on how to uniquely target a specific node within my react reusable component in order to perform operations on it multiple times independently. I will be rendering this reusable component several times on the same page in my App.js. Here is ...

Hiding elements in FireBase and Angular based on user identification

Currently venturing into the world of Firebase in conjunction with AngularJS after previously working with php and server-side rendered pages. I am grappling with how to securely hide specific parts of an application from certain users. I have three disti ...

What is the method for ensuring that the delete functionality is displayed within the same row?

In my division, there are options for names and deletion. It is displayed on my website as: 1.jpg delete The HTML code for the division is: <div id="files1" class="files"> <b class='dataname' >1.jpg</b> <span cla ...

Passing properties from the parent component to the child component in Vue3JS using TypeScript

Today marks my inaugural experience with VueJS, as we delve into a class project utilizing TypeScript. The task at hand is to transfer the attributes of the tabsData variable from the parent component (the view) to the child (the view component). Allow me ...

Encountered a Vercel Error 500 due to an Unexpected token "I" found at position 0

I'm currently working on a new project utilizing a contentful server. When attempting to post an entry to contentful locally, everything works perfectly. However, when deployed on Vercel, I encounter the following error: Unexpected token I in JSON pos ...