#how do i redirect to 404 programmatically
1 messages · Page 1 of 1 (latest)
Hi @scenic plover. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can programmatically redirect to a 404 page using the notFound function or the redirect object in getServerSideProps or getStaticProps.
If you want to redirect to a 404 page, you can use the notFound function. Here's an example:
// No code provided in the extracts
Unfortunately, the extracts do not provide a code example for using the notFound function. You can find more information about it in the Next.js documentation (https://nextjs.org/docs/app/api-reference/functions/not-found).
Alternatively, you can use the redirect object in getServerSideProps or getStaticProps. Here's an example:
export async function getServerSideProps(context) {
const res = await fetch(`<https://.../data`>)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {}, // will be passed to the page component as props
}
}
In this example, if the fetched data does not exist, the user is redirected to the root page (/). You can replace '/' with the path to your custom 404 page if you have one.
Remember, Next.js provides a static 404 page by default without having to add any additional files. If you want to customize the 404 page, you can create a pages/404.js file. This file is statically generated at build time. Here's an example:
export default function Custom404() {
return <h1>404 - Page Not Found</h1>
}