Skip to content

Rewrite to page that redirects (301, 302, etc) results in internal URL change #61631

@abriginets

Description

@abriginets

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/silent-brook-qh9zv9?file=%2Fmiddleware.ts%3A16%2C5&workspaceId=eaa85a37-24ba-4d57-a316-bcdf1a6ac9c8

To Reproduce

TLDR;

  1. Navigate to codesandbox reproduction
  2. Inside of Codesandbox preview, navigate to /assets/image/location/310/310/ADA.webp
  3. Pathname will be changed to /static/cities/310x310/2690.webp

More detailed description of what's going on:

I have the following code in my NextJS middleware to handle images fetching

  if (LOCATION_IMAGE_REGEX.test(request.nextUrl.pathname)) {
    const matches = request.nextUrl.pathname.match(LOCATION_IMAGE_REGEX);
    const width = matches.at(1);
    const height = matches.at(2);
    const code = matches.at(3);
    const extension = matches.at(5);

    return NextResponse.rewrite(`https://photo.hotellook.com/static/cities/${width}x${height}/${code}.${extension}`);
  }

This code is supposed to take pathname /assets/image/location/310/310/ACI.webp and rewrite it to https://photo.hotellook.com/static/cities/310x310/ACI.webp. It worked just fine until https://photo.hotellook.com/static/cities/310x310/ACI.webp started redirecting to https://photo.hotellook.com/static/cities/310x310/30295.webp. So now URLs in my own app is changing from assets/image/location/310/310/ACI.webp to /static/cities/310x310/30295.webp and image obviously cannot be found

Current vs. Expected behavior

Current behavior: rewrite URL can be affected by third party resources.
Expected behavior: rewrite should follow redirects

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP Thu Oct 5 21:02:42 UTC 2023
Binaries:
  Node: 18.14.0
  npm: 9.3.1
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 13.5.6
  eslint-config-next: 13.1.1
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 4.9.4
Next.js Config:
  output: standalone

Which area(s) are affected? (Select all that apply)

Middleware / Edge (API routes, runtime)

Which stage(s) are affected? (Select all that apply)

next start (local)

Additional context

Issue is present in both canary (as of 04.02.2024) and 13.5.6 (currently in production)

Metadata

Metadata

Assignees

No one assigned

    Labels

    RuntimeRelated to Node.js or Edge Runtime with Next.js.bugIssue was opened via the bug report template.lockedstaleThe issue has not seen recent activity.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions