Skip to content

[App Route] How can I redirect to 404 or not-found from the middleware? #52233

Answered by devjiwonchoi
abaracedo asked this question in Help
Discussion options

You must be logged in to vote

First of all, the not-found or notFound is not for "redirecting to 404 page".

It is to throw an error with 404 status and render an alternate UI.

If an user tries to request a URL that doesn't exist I want to redirect them to a 404 page or not-found.tsx

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.

// 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 …

Replies: 4 comments 17 replies

Comment options

You must be logged in to vote
1 reply
@devjiwonchoi
Comment options

Comment options

You must be logged in to vote
10 replies
@chev0004
Comment options

@Shinkei
Comment options

@activenode
Comment options

@Shinkei
Comment options

@denis-maslovskiy-vention
Comment options

Answer selected by abaracedo
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
6 replies
@heymattiarighetti
Comment options

@activenode
Comment options

@heymattiarighetti
Comment options

@LassazVegaz
Comment options

@heymattiarighetti
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet