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

https://i.sstatic.net/aGAgG.png

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

What is causing the lack of updated data on the components when navigating to a different page? (Vue.JS 2)

I am working with 2 components The first component looks like this : http://pastebin.com/M8Q3au0B Due to the long code, I have used pastebin for it The first component calls the second component The second component is as follows: <template> ...

Clickable list element with a button on top

Within my web application, there is a list displaying options for the user. Each 'li' element within this list is clickable, allowing the user to navigate to their selected option. Additionally, every 'li' element contains two buttons - ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

Google Chrome successfully transmits two variables with AJAX, whereas Mozilla Firefox does not send them

Having an issue with sending two values through ajax - currently only one value is being sent in Mozilla browser. Ajax script: $('#post_submit').click(function() { event.preventDefault(); var great_id = $("#post_container_supreme:first").attr(" ...

jQuery Accordian malfunctioning for all elements except the first one in the list

Trying to implement an accordion feature that can be utilized across the entire website. The current logic seems to be partially functional... When I click on any of the accordions, it should open by adding a 'show' class, but this only works for ...

Asynchronous operations and recursive functions in the world of Node.js

When working with express and mongoose, I frequently find myself needing to perform batch operations on collections. However, the typical approach involves callbacks in nodejs concurrency coding, which can be cumbersome. // given a collection C var i = 0 ...

Manipulate text with jQuery

Is there a way to remove 'http://' or 'https://' from text using javascript? I am looking for regex solutions as well. This is what I have tried so far: JSFIDDLE HTML: <div class="string"></div> JS: $text = $('.s ...

Guide to triggering an event when two distinct keys are pressed simultaneously (Using HTML5 and Javascript)

I'm looking to have my character jump whenever I press any key on the keyboard. Is there a method to achieve this using "case..." functions? Thanks! Jordan ...

Running a <script> tag with an external src attribute in a dynamic manner through the use of eval

Currently, I am utilizing the Genius API to fetch lyrics for a particular song and then embed them within an HTML <div> tag. My interaction with this API is through PHP, employing an AJAX GET request. Upon a successful AJAX request, the following HT ...

The updated Bootstrap 4 carousel is only working halfway as expected when attempting to double it up, causing the scroll loop to stop functioning

Discovering a fantastic carousel modification was an exciting find, which can be accessed Here. However, when attempting to place two carousels on one page, issues arose with the scrolling functionality. While I managed to make them operate on the correct ...

What could be causing the appearance of sha256.js when making an AJAX request to a PHP script using jQuery?

Currently, I am executing a script that saves modifications to a PHP script in the background using jquery-ajax. Additionally, I have implemented a function that triggers an error if the script attempts to post something on the site. In case of an error, I ...

Error encountered while attempting to build Ionic 5 using the --prod flag: The property 'translate' does not exist on the specified type

I encountered an error while building my Ionic 5 project with the --prod flag. The error message I received is as follows: Error: src/app/pages/edit-profile/edit-profile.page.html(8,142): Property 'translate' does not exist on type 'EditProf ...

Display a loading image as a placeholder while the Block is loading on the Viewport

Despite my extensive search for a solution to my problem, I have been unable to find one that addresses it directly. I am trying to display a "loading" image for 4 seconds before the content of the div is loaded. Unfortunately, I haven't been able to ...

What is the best way to incorporate items into Redux reducers?

Incorporating Redux with Next JS, I am faced with the challenge of adding an array of objects to it. Within my application, there exists a form containing multiple inputs, and in order to accommodate these inputs, I have structured a form consisting of 10 ...

Using VueJS with Bootstrap 4 themes: A step-by-step guide

There are various Bootstrap 4 themes available that simplify the process of styling and laying out a website. Some of these themes require specific organization of our assets folders. For example: root-folder/ ├── assets/ │ ├── css/ │ ...

What are some solutions for resolving the issue of a neutralino white screen?

After setting up a new neutralino js application, I encountered an issue where upon running it with the 'neu run' command, all I see is a blank white screen. I tried using the CheckNetIsolation.exe ... command to troubleshoot the problem, but unf ...

I'm having trouble getting my application to output to the console. What could be the issue?

In my cr-route.js file, I have a function that ensures the user is authenticated before displaying their name. module.exports = function (app, passport) { // ===================================== // HOME PAGE (with login links) ======== // == ...

The Angular directive was unable to reach the controller located higher up in the DOM hierarchy

template <section id="content" ng-controller="ReservationController as resvnCtrl" > <form role="form" name="resvnCtrl.form"> <div data-date-picker> </div> ...

Toggle the element within the selected row using Jquery

In order to create a client list, users must click on rows to select them and then submit the selections to the database for a cron job to send out emails. Instead of using checkboxes, I am attempting to highlight rows by including two hidden elements - o ...

"What's the best way to update the src attribute of an iFrame when a user clicks

I'm new to coding in PHP or JavaScript, so please bear with me if my question isn't quite right. I'm looking for a way to dynamically pass and embed a URL from a link into the src attribute of an iframe. Essentially, I want users to click o ...