#prefix the local for nextjs url slug

1 messages · Page 1 of 1 (latest)

vivid heron
#

is there a way to prefix the default local for nextjs

sweet pastureBOT
#

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:

  1. Create a next.config.js file 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,
};
  1. 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.

Source: Next.js Documentation - Internationalization Routing (https://nextjs.org/docs/pages/building-your-application/routing/internationalization)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

Next.js has built-in support for internationalized routing and language detection. Learn more here.