Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
Nuxt3 router doesn't push user to certain page

I have two middlewares:

  1. Login page middleware pushes logged in user to his maximum's role allowed dashboard (example: user, owner -> owner / user -> user)
  2. Panel middleware checks user roles and if there's no permission to visit the page it redirects back to login (worker will be redirected to login page if he tries to watch owner dashboard)

To make logout function I created query path in the first middleware (login?logout=true) and when user wants to logout, dashboard should redirect him to login page with this query, though it doesn't

The thing is that when I do redirection, console.log(to) method on the first middleware prints me:

fullPath: "/dashboard/owner"

Redirect method

this.$router.replace({ name: 'login', query: { 'logout': true } })

First middleware

import { authoritiesRoutes } from "~~/middleware/panel"
import { useAuthStore } from "~~/store/auth"

export default defineNuxtRouteMiddleware(async ({ $pinia }, to, from) => {
    const token = useCookie('accessToken')
    console.log(to)

    if (to.query.logout === 'true') {
        token.value = null
        return navigateTo('/login')
    }

    if (token.value) {
        const store = useAuthStore($pinia)
        await store.retrieveUser(token.value)
        if (store.user != null) {
            const permissionLevel = store.getUser.authorities.length
            const routeName = authoritiesRoutes[permissionLevel]
            const route = '/' + routeName.replace('-', '/')
            return route;
        }
    }
})

Second middleware

import { useAuthStore } from '~~/store/auth'

export enum authoritiesRoutes {
    'panel' = 1,
    'dashboard' = 2,
    'dashboard-owner' = 3
}

export default defineNuxtRouteMiddleware(async ({ $pinia, $event }, to) => {
    const token = useCookie('accessToken')

    if (!token.value) {
        return navigateTo('/login')
    }

    const store = useAuthStore($pinia)
    await store.retrieveUser(token.value)

    if (store.user == null) {
        return navigateTo('/login')
    }

    const permissionLevel = authoritiesRoutes[to.name];
    if (store.getUser.authorities.length < permissionLevel) {
        return navigateTo("/login?error=you%20don't%20have%20permission%20to%20watch%20this%20page")
    }
})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I figured out that (async ({ $pinia }, to, from) in the middlewares should be (async (to, { $pinia }) I also found out that useCookie method works only when page is reloaded so I did my task this way:

  1. First middleware
export default defineNuxtRouteMiddleware(async (to, { $pinia }) => {
    var token = useCookie('accessToken')
    const store = useAuthStore($pinia)

    if (to.query.logout === 'true') {
        if (!token.value) {
            return navigateTo('/login')
        }
        token.value = null
        if (process.client) {
            store.logout()
        }
    }

    if (token.value) {
        await store.retrieveUser(token.value)
        if (store.user != null) {
            const permissionLevel = store.getUser.authorities.length
            const routeName = authoritiesRoutes[permissionLevel]
            const route = '/' + routeName.replace('-', '/')
            return route;
        }
    }
})
  1. Second middleware stays the same
  2. Login.vue now has created method that looks like this:
created () {
      if (this.$route.query.logout == 'true') {
        this.$router.go(0)
      }
    }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda