Home > Blockchain >  Redirect 404 to homepage in Nextjs with dynamic routes
Redirect 404 to homepage in Nextjs with dynamic routes

Time:04-23

I am trying to redirect 404 pages to the homepage in Nextjs, but because of a rule in the next.config.js it does not work. Every other 404 redirects to homepage, but anything under the /blog/ route goes to the default Nextjs Error page.

example:

/category-1/post1 redirects to /blog/category-1/post1 and if it does not exists it renders the 404 page but does not redirect to homepage.

Here is my _error.js file and 404.js:

import { useEffect } from "react";
import { useRouter } from "next/router";

// export default function Custom404() ->in 404.js<-
export default function _error() {
  const router = useRouter();

  useEffect(() => {
    router.push("/");
  }, []);

  return null;
}

and my next.config.js file:

module.exports = {
  reactStrictMode: true,
  async redirects() {
    return [
    ...oldBlogRedirectRules(),
    ]
}

// List of old categories
const blogCategoryUrlList = [
  "category-1",
  "category-2",
]

// Redirect old category and posts to /blog/[category]/[slug]
function oldBlogRedirectRules() {
  return blogCategoryUrlList.map((url) => {
    return {
      source: `/${url}/:slug*`,
      destination: `/blog/${url}/:slug*`,
      permanent: true,
    };
  });
}

Also the code in /blog/[category]/[slug].js

export default function Blog({ post }) {
  const router = useRouter();

  if (
    !router.isFallback &&
    ...otherConditions
  ) {
    return <ErrorPage statusCode={404} />;
  }

  return (
    <>
          {router.isFallback ? (
            <h1>Loading...</h1>
          ) : (
            ...whatever 
    </>
  );
}

CodePudding user response:

Update: Answered by @hungdoansy in the comments

I was under the impression since I have made the changes in the _error.js I would not require to make any further changes.

To fix this just import the function from the 404.js file:

import Custom404 from 'pages/404.js';

export default function Blog({ post }) {
  const router = useRouter();

  if (
    !router.isFallback &&
    ...otherConditions
  ) {
    return <Custom404 />;
  }

  return (
    <>
          {router.isFallback ? (
            <h1>Loading...</h1>
          ) : (
            ...whatever 
    </>
  );
}
  • Related