i18nexus/next-i18n-router

Middleware redirect / rewrite

Closed this issue · 4 comments

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.

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);
}

I will try this, thank you :)

@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.

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

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