How to handle infinite redirect in navigation guard?

Hello everyone, Can anyone help me out about the issue infinite redirect when we want to make middleware for the authentication user. So I want when the user has already logged in and then try to access login page again then they hasn't access to it. My code:
// @ts-nocheck
export default defineNuxtRouteMiddleware((to, from) => {
const { isAuthenticated } = useAuth();

// Check if the user is authenticated
if (!isAuthenticated()) {
return navigateTo('/auth/login')
} else {
return navigateTo('/homepage')
}
})
// @ts-nocheck
export default defineNuxtRouteMiddleware((to, from) => {
const { isAuthenticated } = useAuth();

// Check if the user is authenticated
if (!isAuthenticated()) {
return navigateTo('/auth/login')
} else {
return navigateTo('/homepage')
}
})
5 Replies
kapa.ai
kapa.ai2w 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: ---------------------- The issue you're experiencing with infinite redirects in your navigation guard is a common problem when implementing authentication middleware in Nuxt. Based on the knowledge sources provided, I can offer a solution to fix this issue. The main problem in your code is that you're always redirecting, regardless of the current route. This causes the middleware to run repeatedly, leading to an infinite loop. Here's how you can modify your middleware to avoid this:
export default defineNuxtRouteMiddleware((to, from) => {
const { isAuthenticated } = useAuth();

// If the user is not authenticated and trying to access a protected route
if (!isAuthenticated() && to.path !== '/auth/login') {
return navigateTo('/auth/login');
}

// If the user is authenticated and trying to access the login page
if (isAuthenticated() && to.path === '/auth/login') {
return navigateTo('/homepage');
}

// For all other cases, allow the navigation to proceed
return;
});
export default defineNuxtRouteMiddleware((to, from) => {
const { isAuthenticated } = useAuth();

// If the user is not authenticated and trying to access a protected route
if (!isAuthenticated() && to.path !== '/auth/login') {
return navigateTo('/auth/login');
}

// If the user is authenticated and trying to access the login page
if (isAuthenticated() && to.path === '/auth/login') {
return navigateTo('/homepage');
}

// For all other cases, allow the navigation to proceed
return;
});
This modified version addresses the infinite redirect issue by: 1. Only redirecting to the login page if the user is not authenticated and is trying to access a route other than the login page. 2. Only redirecting to the homepage if the user is authenticated and is trying to access the login page. 3. For all other cases, it allows the navigation to proceed without redirection. The key here is to return nothing (which allows the navigation to continue) when no redirection is needed. This approach is supported by the Nuxt documentation on middleware usage Docs > Guide > Directory-structure > middleware (https://nuxt.com/docs/guide/directory-structure/middleware#usage), which states:
Possible return values are: - nothing (a simple return or no return at all) - does not block navigation and will move to the next middleware function, if any, or complete the route navigation
By implementing this logic, you prevent the middleware from constantly redirecting and avoid the infinite loop. Remember to adjust the paths ('/auth/login' and '/homepage') to match your actual route structure if they differ from the example. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
🇨🇭 Marko Bolliger <cannap>
@kapa.ai show i18n example
kapa.ai
kapa.ai2w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Certainly! I'd be happy to show you an example of using i18n (internationalization) in Nuxt. Here's an example based on the knowledge sources provided: First, let's look at the configuration in nuxt.config.ts:
export default defineNuxtConfig({
modules: [
'@nuxtjs/i18n',
],
i18n: {
vueI18n: './translations/i18n.config.ts',
locales: [
{ code: 'sk', iso: 'sk-SK', name: 'Slovenčina' },
// You can add more locales here
],
defaultLocale: 'sk',
strategy: 'prefix_and_default',
customRoutes: 'config',
pages: {
'products/[type]': {
sk: '/produkty/[type]'
},
},
}
})
export default defineNuxtConfig({
modules: [
'@nuxtjs/i18n',
],
i18n: {
vueI18n: './translations/i18n.config.ts',
locales: [
{ code: 'sk', iso: 'sk-SK', name: 'Slovenčina' },
// You can add more locales here
],
defaultLocale: 'sk',
strategy: 'prefix_and_default',
customRoutes: 'config',
pages: {
'products/[type]': {
sk: '/produkty/[type]'
},
},
}
})
This configuration sets up the i18n module with Slovak as the default language and uses the 'prefix_and_default' strategy for URL handling Stack Overflow Post > Dynamic routing in Nuxt 3 with I18n (https://stackoverflow.com/questions/78339975). Next, let's look at the i18n.config.ts file:
import sk from './locales/sk/default.json'

export default defineI18nConfig(() => ({
legacy: false,
locale: 'sk',
fallbackLocale: 'sk',
dynamicRouteParams: true,
messages: {
sk,
}
}))
import sk from './locales/sk/default.json'

export default defineI18nConfig(() => ({
legacy: false,
locale: 'sk',
fallbackLocale: 'sk',
dynamicRouteParams: true,
messages: {
sk,
}
}))
This configuration sets up the i18n instance with Slovak translations Stack Overflow Post > Dynamic routing in Nuxt 3 with I18n (https://stackoverflow.com/questions/78339975). Now, let's see how to use i18n in a component:
<template>
<NuxtLink :to="localePath({ name: 'products-type', params: { type: 'all' } })">
{{ $t('all') }}
</NuxtLink>
<NuxtLink :to="localePath({ name: 'products-type', params: { type: 'favorites' } })">
{{ $t('favorites') }}
</NuxtLink>
</template>

<script setup>
const localePath = useLocalePath()
</script>
<template>
<NuxtLink :to="localePath({ name: 'products-type', params: { type: 'all' } })">
{{ $t('all') }}
</NuxtLink>
<NuxtLink :to="localePath({ name: 'products-type', params: { type: 'favorites' } })">
{{ $t('favorites') }}
</NuxtLink>
</template>

<script setup>
const localePath = useLocalePath()
</script>
In this example, we're using the localePath function to generate localized routes, and the $t function to translate text Stack Overflow Post > Dynamic routing in Nuxt 3 with I18n (https://stackoverflow.com/questions/78339975). To change the language programmatically, you can use the setLocale function:
const changeLangTo = (lang) => {
setLocale(lang)
// Additional logic here
}
const changeLangTo = (lang) => {
setLocale(lang)
// Additional logic here
}
This function can be called to switch between different languages Stack Overflow Post > Nuxt 3 i18n browser detection not working Part 3 (https://stackoverflow.com/questions/77430938). Remember to place your translation files in the appropriate directory structure, typically under a locales folder, with each language having its own JSON file containing the translations. This example provides a basic setup for i18n in Nuxt 3. You can expand on this by adding more languages, creating more complex translation structures, and implementing language detection based on the user's browser settings. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@87630674508394496> 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