i18nexus / next-i18n-router

Next.js App Router internationalized routing and locale detection.
MIT License
260 stars 18 forks source link

Middleware redirect / rewrite #59

Closed enisze closed 8 months ago

enisze commented 8 months ago

Hey I would like to know how I can use rewrite:

return NextResponse.rewrite(newUrl.toString()) or redirect: return NextResponse.redirect(url, { status:200 })

with next-i18n-router. I did not find any documentation in regards to that.

i18nexus commented 8 months ago

Hi there. You can add whatever middleware logic you want. You just have to remember that you have to account for the locale in the path:

export function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;
  const pathLocale = i18nConfig.locales.find(l => pathname === `/${l}` || pathname.startsWith(`/${l}/`);
  const prefix = pathLocale ? `/${pathLocale}` : '';

  if (pathname === `${prefix}/redirect-me") {
    return NextResponse.redirect(new URL(`${prefix}/redirect-destination`, request.url))
  }

  return i18nRouter(request, i18nConfig);
}
enisze commented 8 months ago

I will try this, thank you :)

ddeisadze commented 8 months ago

@enisze did that work? I am trying to do multiple levels of rewrite and end with the i18nRouter(request, i18nConfig) middleware but its not working for me. Only works for redirects.

enisze commented 8 months ago

well I am just checking for the prefix myself sth like this:

    if (pathname.startsWith(`${prefix}/some/pathname`)) {
            ...
            return NextResponse.redirect(newUrl, {
                status: xxx,
            })
        }