'@nuxtjs/auth Why refresh page always redirect to login

I can't refresh page or open new tab of secure page after refresh or new tab will redirect me to login again

Version

Nuxt.js v2.9.1
@nuxtjs/module: 4.8.4

secure page

middleware: ['auth'],

middleware of auth-module

login page

middleware: ['guest'],

middleware/guest.js

export default async function({ store, redirect }) {
    // console.log(store.state.auth)
    if (store.state.auth.loggedIn) {
        return redirect('/')
    }
}

console.log(store.state.auth) = { user: null, loggedIn: false, strategy: 'local' }

nuxt.config.js

auth: {
        strategies: {
            local: {
                endpoints: {
                    // register: { url: 'member', method: 'post', propertyName: 'data.accessToken' },
                    login: { url: 'api/authen-admin', method: 'post', propertyName: 'custom' },
                    user: { url: 'api/admin', method: 'get', propertyName: 'custom' },
                    logout: false
                },
                tokenRequired: 'Authorization',
                tokenType: false
            }
        },
        watchLoggedIn: true,
        localStorage: {
            prefix: 'auth.'
        },
        cookie: {
            prefix: 'auth.', // Default token prefix used in building a key for token storage in the browser's localStorage.
            options: {
                path: '/', // Path where the cookie is visible. Default is '/'.
                expires: 5 // Can be used to specify cookie lifetime in Number of days or specific Date. Default is session only.
                    // domain: '', // Domain (and by extension subdomain/s) where the cookie is visible. Default is domain and all subdomains.
                    // secure - false, // Sets whether the cookie requires a secure protocol (https). Default is false, should be set to true if possible.
            }
        },
        redirect: {
            login: '/login',
            logout: '/login',
            home: '/'
        },
        resetOnError: true
}

I try to use vuex-persist to persist local storage but doesn't work and when login not redirect to home path still stay login path



Solution 1:[1]

maybe you can use nuxtServerInit to check the login user. place in the store/index.js folder as root folder. every time you open the web for the first time, this code will run. example i use the cookie to check user loggedIn or not:

export const actions = {
  async nuxtServerInit ({ commit }, { req }) {
    let auth = null
    if (req.headers.cookie) {
      // cookie found
      try {
        // check data user login with cookie
        const { data } = await this.$axios.post('/api/auths/me')
        // server return the data is cookie valid loggedIn is true
        auth = data // set the data auth
      } catch (err) {
        // No valid cookie found
        auth = null
      }
    }
    commit('SET_AUTH', auth) // set state auth
  },
}

here the documentation

Solution 2:[2]

Extending Fauzan Edris answer.

I was using Auth Nuxt, following fixed my issue.

export const actions = {
  async nuxtServerInit({
    commit
  }, {
    req
  }) {
    let auth = null
    if (req.headers.cookie) {
      // cookie found
      try {
        // check data user login with cookie
        const {
          data
        } = await this.$axios.post('/user/profile')
        // server return the data is cookie valid loggedIn is true
        auth = data.data // set the data auth
      } catch (err) {
        // No valid cookie found
        auth = null
      }
    }

    // How we can set the user for AuthNuxt
    // Source: https://auth.nuxtjs.org/api/auth
    this.$auth.setUser(auth)
  },
}

Solution 3:[3]

You set propertyName of user endpoint to 'custom', do you receive the response with this property name? when page reload, auth plugin will try to fetchUser method to sure client still authenticated, if you didnt config user endpoint correctly, regardless of whether receive, user will set null, so you will redirect to login page, you can check what user property set by run this code:

let user = await this.$auth.requestWith(
    'local', null, { url: 'api/admin', method: 'get', propertyName: 'custom' } );
console.log(user);

Solution 4:[4]

I'm using Nuxt with Laravel Sanctum and the thing that solved the problem for me was an issue with the SESSION_DOMAIN. I'm running the project on a subdomain and the SESSIOn_DOMAIN was set to ".domain.com", but it has to be set to "sub.domain.com".

Solution 5:[5]

I've got same and find out on server message, that looked impossible

[404] /api/admin

So I've tried to add BASE_URL to this request url into nuxt.config.js


auth: {
  strategies: {
    local: {
      endpoints: {
        user: { url: `${BASE_URL}/api/admin`, ... },
    ...
}

and issue gone

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 zarpio
Solution 3 Mohsen
Solution 4 Svetoslav Stefanov
Solution 5 Sasha Kos