For example, we once used getServerSideProps
to redirect to a 404 page in the page component like this:
// pages/index.js export async function getServerSideProps(context) { const placeId = context.params.placeId; const places = await getPlace(placeId); if (!places.length) { return { notFound: true, } } return { props: { places[0], }, };
With the Next.js 13
and app
directories, we have the server component. getServerSideProps
How to redirect to a 404 page when it is no longer in use?
P粉8059224372023-11-04 14:17:20
According to the documentation, you can use the notFound( )
function as shown below, which will render the corresponding not-found.js
document:
// app/user/page.js import { notFound } from 'next/navigation'; export default async function Profile({ params }) { const res = await fetch(`/user/${params.id}`); if (!res.ok) { notFound(); } return <div>Actual Data</div>; }
// app/user/not-found.js export default function NotFound() { return <p>404 Not Found</p> }
If there is no app/user/not-found.js
file, use app/not-found.js
. If there is no app/not-found.js
, it will use the default value given by Next.js.