Is it possible to somehow redirect the user to the home page (/
) instead of displaying the 404 page?
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).
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.
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; };
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With