I
I
Igor2019-07-04 18:44:58
Vue.js
Igor, 2019-07-04 18:44:58

How to check jwt in Nuxt, in "spa" mode?

How to check jwt in Nuxt, in "spa" mode?
Colleagues, the problem is as follows:
The application works in "SPA" mode.
Accordingly, server functions, such as "nuxtServerInit" and others, will work naturally.
When a page is loaded for the first time or an already loaded page is updated, the Middleware does not fire, because the Middleware fires once on the server and subsequent transitions ...
But since we work in SPA mode, we are deprived of the possibility of the first Middleware firing when loading.
But I need to protect the routing on first boot.
This is how I do it:
middleware/check-auth.js

export default async function ({store, req, redirect}) {
    
    if (process.browser){
        
        let auth = isAuth(store.getters['access_token'])
        if(!auth){
            redirect('/login')
        }
   
    }
};

I found a way!
By creating plugin
plugins/nuxt-client-init.js
export default (ctx) => {

    let auth = isAuth(Cookie.get("access_token"))
    
    if(!auth){
        ctx.redirect('/login')
    } else {
        ctx.redirect('/')
    }

}

But it turned out that ctx.redirect('/login') doesn't work and the store hasn't been initialized yet ((
This is how I connect plugins, I wonder, does the load order matter?
/*
    ** Plugins to load before mounting the App
    */
    plugins: [
        { src: '~/plugins/localStorage.js', ssr: false },
        { src: '~/plugins/nuxt-client-init.js', ssr: false }
    ],

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor, 2019-07-04
@IgorPI

Colleagues, everything was resolved as follows:
Occurs only once when the page is refreshed or when it is first loaded on the client side (in the browser)

export default (ctx) => {

    let auth = isAuth(Cookie.get("access_token"))

    if(!auth){
        ctx.redirect('/login')
    } else {
        ctx.redirect('/')
    }

}

Occurs every time the route changes. In spa mode does not work on the server ()
export default async function ({store, req, redirect}) {

    if (process.browser){

        console.log('check auth')
        let auth = isAuth(Cookie.get("access_token"))
        if(!auth){
            redirect('/login')
        }

    }
};

All this together works correctly.
1. On first load or update, nuxt-client-init.js fires
2. Only /middleware/check-auth.js works on navigation

4
4iloveg, 2019-07-04
@4iloveg

A simple redirect to js won't work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question