next.js icon indicating copy to clipboard operation
next.js copied to clipboard

notFound is not working with middleware + fallback

Open ikryvorotenko opened this issue 2 years ago • 0 comments

Verify canary release

  • [X] I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: x64
  Version: Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64
Binaries:
  Node: 18.4.0
  npm: 8.12.1
  Yarn: 1.22.19
  pnpm: 7.8.0
Relevant packages:
  next: 13.0.1
  eslint-config-next: N/A
  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

The static props page with notFound: true result and fallback: true doesn't lead to 404 when it's routed through middleware rewrite.

The bug happens only with the specific page configuration:

  • there's a dynamic page /_test/[id]
  • id = 0 should lead to 404 page
//in getStaticProps
if (id === '0') {
  return {notFound: true}
}
  • there's a rewrite in middlware: /unknown for page /_test/0
//in middlware.ts
if (request.nextUrl.pathname.startsWith('/unknown')) {
  return NextResponse.rewrite(new URL('/_test/0', request.url))
}
  • there's a fallback: true for the page
export async function getStaticPaths() {
  return {paths: [], fallback: true}
}

Current results: http://localhost:3000/_test/0 leads to 404 http://localhost:3000/_test/1 leads to valid page http://localhost:3000/unknown leads to an error caused by incorrect data json loaded

Expected: http://localhost:3000/unknown leads to 404 (the same as /_test/0)

Notes:

  • From my investigation, I can see that due to rewrite, on the /unknown page the data json url is used as / and it leads to incorrect page state.
  • What I also noticed is that if I remove fallback, /unknown would return 404 as expected.

Expected Behavior

The static props page with notFound: true result and fallback: true leads to 404 no matter if it's routed directly or through middlware.

i.e. http://localhost:3000/unknown leads to 404 (the same as /_test/0)

Link to reproduction

https://github.com/ikryvorotenko/nextjs-notfound-middleware-bug

To Reproduce

Run yarn dev Go to http://localhost:3000/unknown

ikryvorotenko avatar Nov 01 '22 16:11 ikryvorotenko