QuiiBz / next-international

Type-safe internationalization (i18n) for Next.js
https://next-international.vercel.app
MIT License
1.19k stars 52 forks source link

Automatically localize from middleware #407

Open davidlewisbates1980 opened 1 month ago

davidlewisbates1980 commented 1 month ago

Describe the bug When creating a fresh NextRequest, it is not automatically localized.

To Reproduce I'm fairly new to all of this, so please be gentle! I've got the following code...

export function middleware(request: NextRequest) {
  if (isPageFeatureDisabled(request.url)) {
    request = new NextRequest(
      new URL("/feature-disabled", request.url), // Since I don't specify a locale prefix, I *assumed* it'd add it for me...
    );
  }

  // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- Middleware return type isn't specified
  return I18nMiddleware(request);
}

What I'm trying to do is to check whether or not the requested URL is allowed (based on our own feature flag system, isPageFeatureDisabled(...)) and, if that page isn't allowed, to send the user the data from /feature-disabled.

I thought that if I just created a new request object and passed it to the localization middleware, it'd automatically add the locale so the page would be displayed in the appropriate language...but this doesn't happen.

Expected behavior If I go to /fr/page-behind-feature-flag, I expected the above code to leave the browser URL unchanged, but to show me the text which is returned from /fr/feature-disabled. However, it instead goes to my default locale and shows me the content from /en/feature-disabled.

Screenshots M/A

About (please complete the following information):

Additional context I'm fairly new to this library and to middleware in general, so it might just be my bug.

davidlewisbates1980 commented 1 month ago

I did find this workaround:

export function middleware(request: NextRequest) {
  if (isPageFeatureDisabled(request.url)) {
    const locale = request.cookies.get("Next-Locale")?.value || defaultLocale;
    return NextResponse.rewrite(new URL(URLBuilder.featureDisabled(locale), request.url));    
  }

  // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- Middleware return type isn't specified
  return I18nMiddleware(request);
}