Replies: 1 comment
-
Usage questions should go in the discussions please. The behavior of handling prefixes with |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Description
Hi
I take as an example a site with two languages, the default is Italian and English is the secondary
for Italian I do not want /it to appear in the urls, while for the English ones it does
export const routing = defineRouting({
locales: ['it', 'en'],
defaultLocale: 'it',
localePrefix: 'as-needed'
});
further down I also report how I solved this problem. The case where the iso code is not used for the default language urls is a very frequent behavior
Verifications
Mandatory reproduction URL
App Router
Reproduction description
I have seen that with this configuration, loading the homepage with
http://localhost:3000/
does not create the cookie
NEXT_LOCALE with the value "it"
instead if I used
http://localhost:3000/it
it does
and also with
http://localhost:3000/en
it creates the cookie NEXT_LOCALE with the value "en"
go from
http://localhost:3000/en
to
http://localhost:3000/it
it changes the value of the cookie from en to it, correctly, in fact
http://localhost:3000/it
becomes
http://localhost:3000/
the problem comes when I go from
http://localhost:3000/en
to
http://localhost:3000/
in this case the cookie value does not become it and therefore the page returns to
http://localhost:3000/en
Expected behaviour
the problem is that the cookie is not created when the language iso code is not present in the url
the problem is solved by creating the cookie also with this url
http://localhost:3000/
which is the case managed with the option
localePrefix: 'as-needed'
I solved it this way into middleware.ts
`import createMiddleware from 'next-intl/middleware';
import { NextResponse, type NextRequest } from 'next/server';
import { routing } from './i18n/routing';
const nextIntlMiddleware = createMiddleware(routing);
export default function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const localeCookie = request.cookies.get('NEXT_LOCALE');
// Only for the root (/)
if (pathname === '/' && localeCookie?.value !== routing.defaultLocale) {
const response = NextResponse.next();
}
return nextIntlMiddleware(request);
}
export const config = {
matcher: [
'/((?!api|trpc|_next|_vercel|.\..).*)'
]
};`
this way when you return to the homepage / the cookie value is always set to the same as the default one
bye
Beta Was this translation helpful? Give feedback.
All reactions