ReactHustle

How to Redirect to 404 Page in NextJS When Using Dynamic Routes

Jasser Mark Arioste

Jasser Mark Arioste

How to Redirect to 404 Page in NextJS When Using Dynamic Routes

Hello, hustlers! In this article, you'll learn how to redirect to 404 page in NextJS inside getServerSideProps or getStaticProps when using dynamic routes or ISR.

If you want to follow along or test it out, I created a sample repo that you can use as a template. Just run this command:

npx create-next-app -e https://github.com/jmarioste/nextjs-redirect-to-404 next-404-redirect

Redirecting to 404 in getServerSideProps #

Suppose you have the route /posts/[slug].tsx, in your getServerSideProps you can do the following redirect to 404 page:

// posts/[slug].tsx
...
export const getServerSideProps: GetServerSideProps = async (
  ctx
) => {
  const slug = ctx.params?.slug as string;
  const post = getPostBySlug(slug) ?? null;

  if (!post) {
    return {
      notFound: true, //redirects to 404 page
    };
  }

  return {
    props: {
      post,
    },
  };
};
1234567891011121314151617181920

In line #6, we get try to get a post by slug

In line #7, we check if the post exists. If it doesn't exist, then return { notFound: true }  to redirect to /404.

The beauty of this approach is that, it will redirect to 404 page automatically without rendering the component since everything is done on the backend. You don't have to check in client side to check if a post is null and use router.push("/404").

If you navigate to a post that doesn't exist  and check the dev tools, it will show the correct status code but it will retain the correct path.

NextJS redirect to 404 page

Redirecting to 404 in getStaticProps #

In getStaticProps, you can use the same technique. Suppose you have a route /tutorials/[slug].tsx, it will be exactly the same as above. For getStaticPaths, I recommend to use fallback: "blocking".

// tutorials/[slug].tsx
...
export const getStaticPaths: GetStaticPaths = async ()=> {
  return {
    paths: [],
    fallback: "blocking"
  }
}

export const getStaticProps: GetStaticProps = async (ctx) => {
  const slug = ctx.params?.slug as string;
  const post = getTutorialBySlug(slug) ?? null;

  if (!post) {
    return {
      notFound: true,
    };
  }

  return {
    props: {
      tutorial: post,
    },
  };
};
12345678910111213141516171819202122232425

Why is it a Bad to Redirect from the Client-side? #

Why is it a bad practice to redirect from the client side? First, it will change the path which is annoying for users. Second it returns a statusCode 200 for the actual path, which is wrong in SEO.

Let's take a look at this example, Suppose you didn't use notFound: true this time:

import { GetServerSideProps } from "next";
import { useRouter } from "next/router";
import React from "react";
import { getPostBySlug } from "../../data/getPostBySlug";
import { Post } from "../../data/Post";

type PostPageProps = {
  post?: Post;
};
const PostPage = (props: PostPageProps) => {
  const router = useRouter();

  if(!props.post && typeof window !== "undefined"){
    router.push("/404")
    return null;
  }
  return (
    <div>
      PostPage
      <h1>{props.post?.slug}</h1>
      <p>{props.post?.content}</p>
    </div>
  );
};

export default PostPage;

export const getServerSideProps: GetServerSideProps = async (
  ctx
) => {
  const slug = ctx.params?.slug as string;
  const post = getPostBySlug(slug) ?? null;

  // if (!post) {
  //   return {
  //     notFound: true,
  //   };
  // }

  return {
    props: {
      post,
    },
  };
};
123456789101112131415161718192021222324252627282930313233343536373839404142434445

In Lines 10-14, We check if the post is null and use the useRouter() hook to redirect to 404.

If you navigate to /posts/that-doesnt-exists and check chrome dev tools, this is what happens:

Incorrectly Redirecting to 404 from&nbsp;Client-side in&nbsp;NextJS&nbsp;

Limitations #

This feature is only available from NextJS v10.0.0

Conclusion #

There are many ways to redirect to 404 in NextJS. But today, we learned on how to properly redirect to 404 in NextJS by returning { notFound: true } in getServersideProps and/or getStaticProps

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter.

Resources #

Related Posts #

Credits: Image by CUONG_ART from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle