1

I am using Next.js i18n-routing in my project and it is working perfect as

  • Index -> /
  • EN -> /about
  • TH -> /th/about

But I want to display default locale value (en) in the url all the time if there is no other language

  • Index page -> /en
  • EN -> /en/about
  • TH -> /th/about

Is there an option from next.js i18n or a way to do this ?

Kaung Khant Zaw
  • 1,508
  • 3
  • 19
  • 31
  • you can use the if statement on entering the user like your app.js. and then if your (if statement) returned true, you can redirect the user to your locale. but you have to make sure your project has different folders for different locales so you would have a cleaner project, – Mohamadreza Kazemian Dec 21 '22 at 05:18

1 Answers1

1

you can do this with Prefixing the Default Locale

first add this to next.config.js:

// next.config.js

module.exports = {
  i18n: {
    locales: ['default', 'en', 'de', 'fr'],
    defaultLocale: 'default',
    localeDetection: false,
  },
  trailingSlash: true,
}

and then create a middleware.ts (or .js) file at the root or in the src directory (same level as your pages). learn more on the new Next.js middleware

// middleware.ts

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') || 'en'

    return NextResponse.redirect(
      new URL(`/${locale}${req.nextUrl.pathname}${req.nextUrl.search}`, req.url)
    )
  }
}

now if there is no specified locale it will fall back to the user locale or en

you can see this example in action here: Edit epic-lumiere-b94rw4

mocherfaoui
  • 902
  • 1
  • 2
  • 11