I am using Next.js i18n-routing in my project and it is working perfect as
/
/about
/th/about
But I want to display default locale value (en) in the url all the time if there is no other language
/en
/en/about
/th/about
Is there an option from next.js i18n or a way to do this ?
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