Support default locale without prefix only for root path #2002
-
I’m trying to configure next-intl v4 with custom routing. Requirements Current attempt import { defineRouting } from 'next-intl/routing';
export const routing = defineRouting({
locales: ['uk', 'en'],
defaultLocale: 'uk',
localePrefix: 'always',
pathnames: {
'/': {
uk: '/',
en: '/en'
}
}
}); Problem Question |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
My current working solution is implemented via a custom middleware.ts. // src/services/i18n/routing.ts
import { defineRouting } from 'next-intl/routing';
export const routing = defineRouting({
locales: ['uk', 'en'],
defaultLocale: 'uk',
localePrefix: 'always',
}); // src/services/i18n/middleware.ts
import createMiddleware from 'next-intl/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { routing } from './routing';
export function createI18nMiddleware(request: NextRequest): NextResponse {
const { pathname } = request.nextUrl;
if (pathname === `/${routing.defaultLocale}` || pathname === `/${routing.defaultLocale}/`) {
const url = request.nextUrl.clone();
url.pathname = '/';
return NextResponse.redirect(url, 308);
}
if (pathname === '/' || pathname === '') {
const url = request.nextUrl.clone();
url.pathname = `/${routing.defaultLocale}`;
return NextResponse.rewrite(url);
}
const handleI18nRouting = createMiddleware(routing);
return handleI18nRouting(request);
} This works as expected: |
Beta Was this translation helpful? Give feedback.
That looks like what I'd suggest too!
Alternate links is maybe something you want to adapt in this case or provide your own implementation (e.g. in a sitemap).