Redirect to 404 Not Found page in Next.js application folder: step-by-step guide
P粉553428780
P粉553428780 2023-11-03 19:55:27
0
1
639

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粉553428780
P粉553428780

reply all(1)
P粉805922437

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template