by Sai gowtham

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

  1. Open the gatsby app in your favorite code editor.
  2. Create a 404.js file inside the src/pages folder and add the following code.
404.js
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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course