Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby redirect to home page instead of displaying 404 page

Tags:

Is it possible to somehow redirect the user to the home page (/) instead of displaying the 404 page?

like image 342
Malakai Avatar asked Aug 06 '18 07:08

Malakai


People also ask

Should I redirect 404 to homepage?

404s should not be redirected globally to the home page. 404s should only be redirected to a category or parent page if that's the most relevant user experience available. It's okay to serve a 404 when the page doesn't exist anymore (crazy, I know).

How do you set the 404 page in The Great Gatsby?

When developing using gatsby develop , Gatsby uses a default 404 page that overrides your custom 404 page. However, you can still preview your 404 page by clicking “Preview custom 404 page” to verify that it's working as expected. This is useful when you're developing so that you can see all the available pages.


2 Answers

Other answers here will eventually fail because the window object is not defined at build time. Use this instead. The useEffect hook is equivalent to componentDidMount.

import { useEffect } from 'react'; import { navigate } from "@reach/router"  export default () => {   useEffect(() => {     navigate('/your-redirect/');   }, []);   return null; }; 
like image 73
Charming Robot Avatar answered Sep 21 '22 10:09

Charming Robot


Gatsby creates 404 page from src/pages/404.jsx (or 404.js if you are not using jsx extension). So, creating a component which redirects to the home page there should do trick, something like this:

import React from 'react';  export default function NotFound() {   if (typeof window !== 'undefined') {     window.location = '/';   }    return null; } 
like image 25
Gokhan Sari Avatar answered Sep 19 '22 10:09

Gokhan Sari