Middleware interaction with router.push causes an infinite loop.
The issue involves an infinite loop when using router.push with the 'as' parameter alongside middleware. The problem is reproducible and affects routing behavior. The fix requires understanding middleware and routing interactions in Next.js.
https://github.com/KmaCoder/reproduce-router-middleware-bug
import { NextMiddleware } from 'next/server';
export const middleware: NextMiddleware = (req) => {
console.log(`> middleware req.url ${req.url}`)
};
router.push with an "as" parameter// On the index page make a redirect to some other page,
// with an 'asPath' = '/' to be shown in browser search bar
void router.push('/home-redirect', '/')
The page does not change, in network there is an infinite loop of fetching the page JSON /_next/data/.
With middleware.ts:
The page changes to the specified one, while the pathname in the browser equals to the as param.
Without middleware.ts, works as expected:
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 22.6.0: Wed Jul 5 22:22:05 PDT 2023; root:xnu-8796.141.3~6/RELEASE_ARM64_T6000
Binaries:
Node: 18.17.0
npm: 9.6.7
Yarn: N/A
pnpm: N/A
Relevant Packages:
next: 14.0.4-canary.1
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
typescript: 5.1.3
Next.js Config:
output: N/A
Middleware / Edge (API routes, runtime), Routing (next/router, next/navigation, next/link)
Reproducible since the middleware
Claim this issue to let others know you're working on it. You'll earn 20 points when you complete it!