#prefix the local for nextjs url slug
1 messages · Page 1 of 1 (latest)
Hi @vivid heron. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, there is a way to prefix the default locale in Next.js using a workaround with Next.js 12 and Middleware. Here's an example of how to do it:
- Create a
next.config.jsfile with support for a few languages. Note that the"default"locale has been added intentionally.
module.exports = {
i18n: {
locales: ['default', 'en', 'de', 'fr'],
defaultLocale: 'default',
localeDetection: false,
},
trailingSlash: true,
};
- Use Middleware to add custom routing rules:
import { NextRequest, NextResponse } from 'next/server';
const PUBLIC_FILE = /\.(.*)$/;
export async function middleware(req: NextRequest) {
if (
req.nextUrl.pathname.startsWith('/_next') ||
req.nextUrl.pathname.includes('/api/') ||
PUBLIC_FILE.test(req.nextUrl.pathname)
) {
return;
}
if (req.nextUrl.locale === 'default') {
const locale = req.cookies.get('NEXT_LOCALE')?.value || 'en';
return NextResponse.redirect(
new URL(
`/${locale}${req.nextUrl.pathname}${req.nextUrl.search}`,
req.url,
),
);
}
}
This Middleware skips adding the default prefix to API Routes and public files like fonts or images. If a request is made to the default locale, it redirects to the prefix /en.