I have a Nuxt project running without server-side rendering i.e. entirely client-side only.
A middleware script queries a remote API to see whether the user must re-login. If so, a redirect to the login page is fired:
/middleware/checkLogin.js:
import {apiReq} from '~/assets/js/utils'
export default async ctx => {
let privateRoute = ctx.store.state.privateRoutes.includes(ctx.route.name);
//is logout request - nothing check required
if (ctx.route.name == 'index' && ctx.route.query.logout) return;
//check login and react accordingly
let res = await apiReq.call(ctx, 'checkLogin');
if (res === null) return;
privateRoute && !res.data.result && redir('/?promptLogin=1');
!privateRoute && res.data.result && redir('/animals');
}
const redir = route => onNuxtReady(() => $nuxt.$router.push(route));
The issue I've got is that despite the redirect, the lifecycle is continuing on to load the page (the one the user shouldn't be able to access) including its asyncData etc.
pages/somePrivatePage.vue
export default {
asyncData() {
//this still runs, even if middleware logged a redirect
}
}
Desired result: when the redirect is logged, subsequent lifecycle steps don't run.
Is there any way I can achieve this? I could log something in state from middleware, and use that as a condition in the asyncData so it doesn't execute, but that seems hacky.
/middleware/checkLogin.js
if (privateRoute && !res.data.result) {
ctx.store.commit('dontDoStuff', 1);
redir('/?promptLogin=1');
}
/pages/somePage.vue
asyncData({store}) {
if (store.state.dontDoStuff) return;
//then this won't run...
}
The issue is the middleware is using $nuxt.$router.push, which just pushes a new route instead of redirecting.
The Nuxt context includes a redirect function that should be used for redirection:
// middleware/checkLogin.js
export default async ctx => {
โฎ ๐
privateRoute && !res.data.result && ctx.redirect('/?promptLogin=1')
!privateRoute && res.data.result && ctx.redirect('/animals')
} ๐