Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Nuxt - quit the lifecycle on redirect?

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...
}
about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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')
}                                             ๐Ÿ‘†

demo

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!