nuxt-modules / i18n

I18n module for Nuxt
https://i18n.nuxtjs.org
MIT License
1.75k stars 483 forks source link

switchLocalePath returns an empty string when used in middleware #3023

Closed eliaSchenker closed 4 months ago

eliaSchenker commented 4 months ago

Environment

Reproduction

https://stackblitz.com/edit/bobbiegoede-nuxt-i18n-starter-zxh9bp

Describe the bug

The switchLocalePath function seems to behave very strangely when used outside of a template. As the reproduction shows the function works in the template of both a page and a component but strangely only functions properly in the script setup of the page, not the component. Furthermore it also doesn't seem to work inside of a middleware. In cases where it doesn't work, it returns an empty string:

[middleware] Doesnt work here: 
[component] Doesnt work here: 
[page] Works here: /nl

We started experiencing this issue after upgrading from Nuxt 3.9.1 to 3.12.3 (before switchLocalePath worked fine everywhere). We rely on using switchLocalePath in a middleware to trigger a custom redirect to the correct locale.

After looking quickly into the code of the function, an empty string is returned if the name of the route isn't given (https://github.com/nuxt-modules/i18n/blob/2887904f53ca94bd73f91dd3bf335f9850c9e8fb/src/runtime/routing/compatibles/routing.ts#L251C3-L253C4), could it be that the behaviour of the nuxt router was altered in a new release, causing this issue?

A possible workaround might be to make the route parameter of the function accessible.

Additional context

No response

Logs

No response

BobbieGoede commented 4 months ago

You're not passing a locale code to switchLocalePath in your reproduction ('/nl' should be 'nl').

Usage within a middleware seems to work except for the initial page load, I suppose this is because the current route is still undefined at that point, I recommend using localePath(route, locale) there instead. If this did work in an older version of Nuxt then maybe the route was not undefined on page load in that version? 🤔

Closing this as things seem to be working as intended, let me know if you have any questions, will reopen if something is amiss.

eliaSchenker commented 4 months ago

Thanks for your quick reply! Yes, that's my bad, the switchLocalePath should be 'nl' not /nl as you said. I also suspect that something was changed in the routing behaviour so that the route is undefined in the middleware. Using localePath with to.path instead of switchLocalePath works perfectly:

// Called from /en/test, for example.
export default defineNuxtRouteMiddleware(async (to, from) => {
    console.log(localePath(to.path, 'nl')); // Prints /nl/test
}