Redirecting to a Home page instead of 404 page in Gatsby
In this tutorial, we will learn how to redirect a user to Home page (/) instead of displaying the (Not found) 404 page in Gatsby.
Redirecting to Home page
-
Open the gatsby app in your favorite code editor.
-
Create a
404.jsfile inside thesrc/pagesfolder and add the following code.
import React, { useEffect } from "react";
import { navigate } from "gatsby";
export default function NotFoundPage() {
useEffect(() => {
navigate("/"); // redirecting to home page }, []);
return (
<div>
<h1>(404) NotFound Page</h1>
</div>
);
}In the above code, we first imported the navigate() method from the gatsby package and invoked it inside the useEffect() hook by passing a homepage path /, so that it redirects a user to Home page whenever he/she visits a 404 page.
Note: The
useEffect()hook with a second argument empty[]array acts like componentDidMount lifecycle method in class components.


