Issue with NextResponse.rewrite(). It redirects instead of rewrites

Hi,

I have a problem with the rewrite() method of the NextResponse function inside middleware.
It works perfectly, but on the index page, it actually redirects to /en for some reason. The website is - https://preview.edgeless.systems

Here is the middleware.ts content:

import { i18n } from "@/i18n.config";
import { match as matchLocale } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

function getLocale(request: NextRequest): string | undefined {
  const negotiatorHeaders: Record<string, string> = {};
  request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));

  const locales = i18n.locales;
  const languages = new Negotiator({ headers: negotiatorHeaders }).languages();

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

  console.log("===================================");

  console.log("Pathname:", pathname);

  // Redirect if there is no locale
  if (pathnameIsMissingLocale) {
    const locale = getLocale(request);

    if (locale === i18n.defaultLocale) {
      const url = new URL(
        `/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}`,
        request.url,
      );

      console.log("URL: " + url.toString());

      return NextResponse.rewrite(url);
    }
  }
}

export const config = {
  matcher: [`/((?!_next|svg|meta|api|slice-simulator|sitemap.xml|icon.svg).*)`],
};

Edge Functions Logs:

Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] ===================================
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] Pathname: /
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] Locale: en
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] Languages: [ "uk", "en" ]
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] Locales: [ "en", "de" ]
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] Default Locale: en
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] Is defaultLocale
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] URL: https://preview.edgeless.systems/en/
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] ===================================
Apr 21, 02:28:50 PM: 01HW0A2V info   [___netlify-edge-handler-src-middleware] Pathname: /en   <- REDIRECTED
Apr 21, 02:28:51 PM: 01HW0A2W info   [___netlify-edge-handler-src-middleware] ===================================

Please note, it happens with the index page only. There are no redirects anywhere in the project.
No problem locally and on Vercel. It happens only on Netlify.

Stack used:

Next.js 14.1
Next.js Runtime - v5.1.2

Content of autogenerated netlify.toml:
[[redirects]]
from = "/_next/image"
to = "/.netlify/images?url=:url&w=:width&q=:quality"
status = 200

  [redirects.query]
  url = ":url"
  w = ":width"
  q = ":quality"

[[redirects]]
from = "/_ipx/*"
to = "/.netlify/images?url=:url&w=:width&q=:quality"
status = 200

  [redirects.query]
  url = ":url"
  w = ":width"
  q = ":quality"

[context]

  [context.production]

  [context.main]

That redirect seems to be coming from your code for the / page and not the middleware. As far as I can see, the middleware is working as expected and for the same request, this function: Function details | Functions | Logs | edgeless3-preview | Netlify also gets invoked (as expected due to rewrite()). The 308 comes from there.

These are the logs produced for a single request:

Netlify Edge Functions:

   ┌─message───────────────────────────────────┐
1. │ ===================================       │
2. │ Pathname: /                               │
3. │ Locale: en                                │
4. │ Languages: [ "en" ]                       │
5. │ Locales: [ "en", "de" ]                   │
6. │ Default Locale: en                        │
7. │ Is defaultLocale                          │
8. │ URL: https://preview.edgeless.systems/en/ │
   └───────────────────────────────────────────┘

---

Netlify Functions:

   ┌─message────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
1. │ REPORT RequestId: 33fb0aa5-a5a1-491f-8624-1ce2edfdd5c2     Duration: 104.72 ms     Billed Duration: 105 ms Memory Size: 1024 MB    Max Memory Used: 157 MB     │
   └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

I also tried this in a minimal setup: hrishikesh-k/f-116856 (github.com), but going to the about URL: 662512f36e15edb636fb4784–f-116856.netlify.app/about/ loads the dashboard page without any redirect.

Mind sharing your repo so we can investigate further?

that’s weird as the problem happens with the index page only. I don’t have redirect rules anywhere in the project. I am not sure I can share the repo, but here is a zip with the code - WeTransfer - Send Large Files & Share Photos Online - Up to 2GB Free

The reasons I think this is Netlify issues are:

  1. No problem locally;
  2. No problem on Vercel - https://edgeless-systems-vbkq-gykvmx1xk-vladyslav-ls-projects.vercel.app
  3. Netlify just released a new Next.js Runtime;

However, thanks for your help, and I will be glad if there is an issue with my code :slight_smile:

Any updates @hrishikesh ? :slight_smile:

You’re right, I was able to reproduce this issue with your repo. Will check further and update.

I’ve escalated this to the devs. Thank you for sharing the code.

Okay, thanks for letting me know.
Will you be able to notify me once the issue is fixed?

Hi, I’ve subscribed to the issue. We will follow up here with an update from the devs when we have it. (:

This should be fixed in v5.2.2 of Next.js Runtime.

it works. Thanks a lot!