Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GatsbyJS: Display 404 page if route doesn't exist

How to correctly set up 404 page, so that if user hits any route that does not exist, it redirects to this 404 page?

Currently I have this code:

import React from "react";
import Layout from "../components/layout";
import SEO from "../components/seo";

    const NotFoundPage = () => (
        <Layout>
            <SEO title="404: Not found" />
            <h1>NOT FOUND</h1>
            <p>You just hit a route that doesn&#39;t exist... the sadness.</p>
        </Layout>
    );
    
    export default NotFoundPage;
like image 776
TheRoyality Avatar asked Nov 16 '25 04:11

TheRoyality


1 Answers

If the file is called 404.js and you place it under src/pages/404.js directory, it will make automatically the redirect for every non-existing page. According to their documentation:

To create a 404 page create a page whose path matches the regex ^\/?404\/?$ (/404/, /404, 404/ or 404). Most often you’ll want to create a React component page at src/pages/404.js.

Keep in mind that under develop mode your 404, Gatsby overrides the default page and lists all your created pages and paths. 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.

Under build mode everything works as expected.

like image 71
Ferran Buireu Avatar answered Nov 17 '25 20:11

Ferran Buireu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!