How to change the root of route in NUXTJS3

For example, the current route will be redirected to '/' and I want to redirect to something like '/auth/login' while accessing the root of route.
2 Replies
kapa.ai
kapa.ai4w ago
Hi @Adnan Erlansyah. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To change the root route in Nuxt 3 and redirect it to a different path like '/auth/login', you can use route middleware or the routeRules configuration. Here are two approaches you can consider: 1. Using Route Middleware: You can create a global route middleware to handle the redirection:
// middleware/redirect.global.ts
export default defineNuxtRouteMiddleware((to) => {
if (to.path === '/') {
return navigateTo('/auth/login')
}
})
// middleware/redirect.global.ts
export default defineNuxtRouteMiddleware((to) => {
if (to.path === '/') {
return navigateTo('/auth/login')
}
})
This middleware will run on every route change and redirect the root path '/' to '/auth/login' Docs > Guide > Directory-structure > middleware (https://nuxt.com/docs/guide/directory-structure/middleware). 2. Using routeRules in nuxt.config.ts: Alternatively, you can use the routeRules configuration in your nuxt.config.ts file:
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/': { redirect: '/auth/login' }
}
})
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/': { redirect: '/auth/login' }
}
})
This configuration will redirect the root path '/' to '/auth/login' Config > Routing > routeRules (https://nitro.unjs.io/config#routerules). Both methods will achieve the desired result of redirecting the root route to '/auth/login'. The route middleware approach gives you more flexibility if you need to add additional logic, while the routeRules configuration is simpler if you just need a straightforward redirect. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4w ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Want results from more Discord servers?
Add your server