[App Route] How can I redirect to 404 or not-found from the middleware? #52233
-
SummaryI'm using the latest version of NextJS (v13.4) and I've created a middleware for checking some URLs. If an user tries to request a URL that doesn't exist I want to redirect them to a 404 page or I'm not sure if the solution should be creating a Edit: I've found this question but for v12 but it doesn't work as Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 19 replies
-
Same for me. Extremely annoying. Next13 and Vercel is not professional business that we can rely on, and it's a childish product with so many bugs, and you can't even do the basics. We will be moving away from this nonsense. Next 13 is a joke. Never in my life have I had to waste months on making middleware, authentication, access checks, and basic errors like 404 work properly in an enterprise B2B platform. For now, another ugly solution I had to implement to make 404 work from a middleware:
Apart from that:
export default function NotFoundCatchAll() {
notFound();
} |
Beta Was this translation helpful? Give feedback.
-
First of all, the It is to throw an error with 404 status and render an alternate UI.
You do not need a middleware for this, the Try to set your // app/not-found.tsx
import Link from 'next/link'
export default function NotFound() {
return (
<div>
<h2>Not Found</h2>
<p>Could not find requested resource</p>
<Link href="/">Return Home</Link>
</div>
)
} Note that you can also trigger the Reference |
Beta Was this translation helpful? Give feedback.
-
what about nextjs pages router? |
Beta Was this translation helpful? Give feedback.
-
Vercel logs an "Error: Failed to execute 'error' on 'Response': the method is not implemented." 👉 Luckily, I found a solution NextResponse.rewriteInside my middleware file, instead of returning NextResponse,error(), I did this:
Now it works properly 👌 The URL is preserved, and the page is rendered as per your not-found.tsx file, as would happen with other not-found pages Hope it helps! |
Beta Was this translation helpful? Give feedback.
First of all, the
not-found
ornotFound
is not for "redirecting to 404 page".It is to throw an error with 404 status and render an alternate UI.
You do not need a middleware for this, the
not-found
file does the work for you.Try to set your
not-found
on the root segment of your route (e.g.app/not-found.tsx
), and will resolve your issue.Note …