If the default language is selected, it should not appear in the URL
Unanswered
Atlantic cod posted this in #help-forum
Atlantic codOP
in the localization example for next13 app directory
https://github.com/vercel/next.js/tree/canary/examples/app-dir-i18n-routing
When we use this, I want to prevent it from appearing in the url in the default language selection.
When I do it for next-intl, it happens like this, but
import { match as matchLocale } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
I could not achieve this with the libraries used in the example.
function getLocale(request: NextRequest): string | undefined {
const negotiatorHeaders: Record<string, string> = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
const locales: string[] = i18n.locales
let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales
)
const locale = matchLocale(languages, locales, i18n.defaultLocale)
return locale
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(
)
if (pathnameIsMissingLocale) {
const locale = getLocale(request)
if (locale === i18n.defaultLocale) {
return NextResponse.redirect(new URL(pathname, request.url))
}
return NextResponse.redirect(
new URL(
request.url
)
)
}
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}
can i get this ?
https://github.com/vercel/next.js/tree/canary/examples/app-dir-i18n-routing
When we use this, I want to prevent it from appearing in the url in the default language selection.
When I do it for next-intl, it happens like this, but
import { match as matchLocale } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
I could not achieve this with the libraries used in the example.
function getLocale(request: NextRequest): string | undefined {
const negotiatorHeaders: Record<string, string> = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
const locales: string[] = i18n.locales
let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales
)
const locale = matchLocale(languages, locales, i18n.defaultLocale)
return locale
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(
/${locale}/) && pathname !== /${locale})
if (pathnameIsMissingLocale) {
const locale = getLocale(request)
if (locale === i18n.defaultLocale) {
return NextResponse.redirect(new URL(pathname, request.url))
}
return NextResponse.redirect(
new URL(
/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname},request.url
)
)
}
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}
can i get this ?