Upon page reload in Nuxt.js middleware, Firebase authentication is returning as null

Just started with nuxtjs and using the Nuxt firebase library for firebase integration. After a successful login, I'm redirecting the user to the "/member/desk" route. However, if I refresh the page on that particular route, it redirects me back to "/auth/signin". This happens because in the "middleware/auth.js" file, I am not receiving the value of app.$fire.auth.currentUser as null.

I tried searching online for a solution but couldn't find any reliable information. Any help would be appreciated.

Here are the relevant sections of my files:

  • nuxt.config.js
[
    '@nuxtjs/firebase',
    {
        config: {
            apiKey: "",
            authDomain: "",
            projectId: "",
            storageBucket: "",
            messagingSenderId: "",
            appId: "",
            measurementId: ""
        },
        services: {
            auth: {
            persistence: 'local', // default
            initialize: {
                onAuthStateChangedAction: 'onAuthStateChangedAction',
                subscribeManually: false
            },
            ssr: false
            }
        }
    }
]
  • store/index.js
// Code for store/index.js goes here...
  • middleware/auth.js
// Code for middleware/auth.js goes here...
  • pages/index.js
// Code for pages/index.js goes here...

--- UPDATE ---

Recently implemented "Firebase Auth with SSR" and was able to partially resolve the issue. Now, when I refresh normally on the "/member/desk" route, it works fine (stays on the same page). However, when I do a HARD RELOAD, it redirects to the "/auth/signin" route.

I suspect it has something to do with the implementation of the Service Worker. On HARD RELOAD, all cached data is cleared and the Service Worker restarts.

If anyone can provide some clarity on this, it would be greatly appreciated!

Answer №1

The firebase authentication documentation states that the currentUser property can be null if the auth object has not finished initializing. In this case, using an observer to monitor the user's login status will handle this scenario automatically.

This means that if your middleware is triggered before the auth.onStateChanged event has completed, the app.$fire.auth.currentUser will initially be null.

It is recommended to modify your middleware to utilize the user data stored in your Vuex store instead.

export default function ({ store, app, route, redirect }) {
    const user = store.state.user;
    if (route.path === '/') {
        // Keep them on the sign-in page
    } else if (route.path !== '/auth/signin') {
        // We are accessing a protected route
        if (!user) {
            // Redirect to sign-in page
            return redirect('/auth/signin')
            // return redirect('/auth/signout')
        }
    } else if (route.path === '/auth/signin') {
        if (!user) {
            // Show the sign-in page
        } else {
            return redirect('/')
        }
    }
}

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

Refreshing a div using ajax technology

I am attempting to use Ajax to update an h3 element with the id data. The Ajax call is making a get request to fetch data from an API, but for some reason, the HTML content is not getting updated. This is how the JSON data looks: {ticker: "TEST", Price: 7 ...

Creating a shared observable array in KnockoutJs to be used for multiple select elements

When an employer needs to assign a specific employee and premium amount, they can click on the "Add Employee" button to reveal another form with a dropdown menu of employees and an input field for the premium amount. <select> <option>John& ...

Updating a singular value in an array using jQuery/JavaScript

Within a Javascript function, I have created an array called HM_Array1. The contents of the array are listed below: HM_Array1 = [[,11,147,,,,,,,1,1,0,0,0,1,"csiSetBorder(this)","null",,,true,["&nbsp;&nbsp;&nbsp;Accoun&nbsp;&nbsp;& ...

Navigate down to the bottom of the element located on the webpage

I'm trying to create a feature where clicking an anchor tag will smoothly scroll to a specific element on the page. Currently, I am using jquery scrollTo for this purpose. Here's the code snippet: $.scrollTo( this.hash, 1500, { easing:&apos ...

How to disable the onChange event in PrimeNG p-dropdown?

I'm currently utilizing PrimeNG's dropdown component. Each option in the list includes an icon that, when clicked, should trigger a specific method. Additionally, I need to execute another method when the onChange event of the dropdown is trigger ...

Not enough test coverage with Jest

Here is the code snippet I am working with: <ReturnToLastSearch href={'/listings'} onClick={(e): void => { e.preventDefault(); router.back(); }} /> The function ReturnToLastSearch( ...

The external javascript file is unable to recognize the HTML table rows that are dynamically inserted through an AJAX request

I have a situation where I'm pulling data from an SQL database and integrating it into my existing HTML table row. Here's the code snippet: Using Ajax to fetch data upon clicking analyze_submit: $(document).ready(function(e) { $('#anal ...

The paragraph text should dynamically update upon clicking a button based on JavaScript code, however, the text remains unchanged despite attempts to modify it

I recently started learning JavaScript and wanted to update the content of a paragraph when a button is clicked. However, I encountered an issue where this functionality doesn't seem to work. <body> <p id="paragraph">Change Text on cl ...

Tips for automatically updating a MaterialUI DataGrid in a React JS application

Here's an overview of my current project: Users can save rows from deletion by clicking checkboxes (multiple rows at a time). Any unchecked records are deleted when the user hits the "purge records" button. I received some guidance on how to achieve ...

Avoiding unnecessary re-renders in your application by utilizing the useRef hook when working with

To prevent the component from re-rendering every time the input value changes, I am trying to implement useRef instead of useState. With useState, the entire component re-renders with each key press. This is the usual approach, but it causes the entire co ...

Adding several <div> elements with the correct indices

I need help with a dynamic form that requires users to select a state before revealing the corresponding cities within that state. <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="s ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

Implement Material UI Textfield with 'error' and 'helper text' for items within a repeated loop

I am currently working on developing an application that involves dynamic text field input using MUI textfield. This application consists of two fields - From and To. The functionality includes generating two new fields when the user clicks on the "Add New ...

Is there a way to retrieve the Angular-Redux store in a child module?

Within my Angular application, I utilize angular-redux for managing the application state. In my main module, I have defined the redux store in the following manner: export class MainModule { constructor(private ngRedux: NgRedux<MainAppState>, ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

Accessing a Variable in one JavaScript File from Another JavaScript File

In the process of creating a basic game using only JavaScript and jQuery, I have split it into two separate pages. The first page contains all the rules and necessary information, while the second page is where the actual game takes place. My goal is to in ...

Display modal after drop-down selection, triggered by API response

Currently, I am working on integrating an API to enable users to make payments through a modal. Users should be able to enter an amount and select a payment frequency. I have successfully extracted various payment frequencies from the API response and pop ...

If an Angular reactive form component has a particular value

I am working with a group of radio buttons. When a user chooses the option "yes," I would like to display an additional input box on the form. Link to Code Example HTML.component <div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt- ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...