3

Gatsby makes it easy to create your own custom 404 page docs here, but I would like to display the URL on the page inside a message - something like:

There was no page at '/example/nope'.

Is there any way to access the failed URL from within the 404 page?

Although I can't find any docs related to it, it appears that the 404 page receives a history object as one of its props, however this object doesn't actually contain any historical URLs, only an api to navigate to a previous state and the current url (which is /404).

Undistraction
  • 42,754
  • 56
  • 195
  • 331

1 Answers1

3

I looked at how Gatsby handles it for its own development 404 page and here are the relevant lines from `gatsby/dist/internal-plugins/dev-404-page/raw_dev:

 render() {
    const pathname = this.props.location.pathname
    ...
    return (
      ...
        <p>
          {`There's not a page yet at `}
          <code>{pathname}</code>
        </p>
     )
   }

So it is using the location.pathname of the props object which refers not to the current 404 page url, but the url of the page that caused the 404.

Note: this won't work if you visit /404 to see your own 404 page in development as the 404 is not being generated in response to a missing page, so location.pathname will be /404

Undistraction
  • 42,754
  • 56
  • 195
  • 331