question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Next.js attempts to fetch API route proxy as regular page

See original GitHub issue

Verify canary release

  • I verified that the issue exists in Next.js canary release

Provide environment information

    Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 21.4.0: Fri Mar 18 00:46:32 PDT 2022; root:xnu-8020.101.4~15/RELEASE_ARM64_T6000
    Binaries:
      Node: 16.15.0
      npm: 8.5.5
      Yarn: 1.22.18
      pnpm: N/A
    Relevant packages:
      next: 12.1.7-canary.40
      react: 18.2.0
      react-dom: 18.2.0

What browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Describe the Bug

When proxying a page using an API route, Next.js will attempt to request the page’s JavaScript at the rewrite destination instead of the source page. For example, with the following rewrite setup, a request to http://localhost:3000?proxy=true will return the correct HTML but then Next.js will send a request to http://localhost:3000/_next/static/chunks/pages/api/proxy.js. That request will 404, resulting in a full page reload, which then results in the same behavior, again and again in an infinite loop.

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  async rewrites() {
    return {
      beforeFiles: [
        {
          source: '/:path(.*)',
          has: [{ type: 'query', key: 'proxy', value: 'true' }],
          destination: '/api/proxy?path=:path',
        },
      ],
    }
  },
}

module.exports = nextConfig

Expected Behavior

The expected behavior is for Next.js to request the page’s JS and not to use the rewrite source to determine the URL.

Link to reproduction

https://github.com/migueloller/next-proxy-rewrite-bug

To Reproduce

git clone https://github.com/migueloller/next-proxy-rewrite-bug
cd next-proxy-rewrite-bug
yarn install
yarn dev
open http://localhost:3000?proxy=true

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:12 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
wyattjohcommented, Jul 5, 2022

#38340 combined with #37949 does solve a problem though, in that we no longer fetching a JS chunk for pages that have prefix of /api. Additionally, this ensures that any use of <Link /> on a route that is rewritten (or sent directly to) one of these routes results in a hard navigation. These routes typically can’t be handled as a client side transition anyways, these changes enable the correct behaviour.

As for handling the redirection loop that’s occurring for your proxying use case, that’s something that we’ll need to handle as a part of the hydration phase. I’d like to keep this issue open as we explore a solution to either providing a more concrete error or direction on how to handle this case.

1reaction
ijjkcommented, Jun 28, 2022

Re-opening as it seems we are hard navigating to the rewrite destination incorrectly instead of the initial provided route when the rewrite is detected.

Will continue discussion around alternatives to avoid the hard navigation in slack thread.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Proxy to backend with default Next.js dev server - Stack Overflow
Another solution with catch-all routes + http-proxy-middleware : // pages/api/proxy/[...slug].js import { createProxyMiddleware } from ...
Read more >
Proxy api requests w/oa custom server #14057 - vercel/next.js
So I went ahead and found a way to proxy api requests to another server with nextjs builtin "Catch all API routes" capability,...
Read more >
next-http-proxy-middleware - npm
Try using Next.js Rewrites(recommended) ... This function is supported by Next.js. No additional libraries need to be installed! https://nextjs.
Read more >
API Routes - Data Fetching - Next.js beta docs
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a route. For...
Read more >
Advanced Features: Custom Server - Next.js
Before deciding to use a custom server, please keep in mind that it should only be used when the integrated router of Next.js...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found