gatsby: 404 page keeps a stale location.pathname from build time

Description

On Gatsby sites, navigating directly to a nonexistant page results in a location object with stale values. The location isn’t rehydrated, and retains its values from build time. For instance, location.pathname will always read 404.html.

This is not an issue when clicking a bad internal link / using client-side routing. It only occurs on direct navigation.

Steps to reproduce

Source for this page: https://github.com/rileyjshaw/rileyjshaw.github.io/blob/dev/src/pages/404.js#L33

Expected result

  • “old website” should link to v14.rileyjshaw.com/no-page here

Actual result

  • “old website” links to v14.rileyjshaw.com/404.html

Environment

System: OS: macOS Mojave 10.14.6 CPU: (4) x64 Intel® Core™ i7-6567U CPU @ 3.30GHz Shell: 3.2.57 - /bin/bash Binaries: Node: 13.9.0 - ~/.nvm/versions/node/v13.9.0/bin/node Yarn: 1.22.0 - /usr/local/bin/yarn npm: 6.13.7 - ~/.nvm/versions/node/v13.9.0/bin/npm Languages: Python: 3.7.4 - /Users/riley/.pyenv/shims/python Browsers: Chrome: 81.0.4044.138 Safari: 13.1 npmPackages: gatsby: ^2.21.36 => 2.21.36 gatsby-image: ^2.4.4 => 2.4.4 gatsby-plugin-feed: ^2.5.1 => 2.5.1 gatsby-plugin-manifest: ^2.4.5 => 2.4.5 gatsby-plugin-offline: ^3.2.3 => 3.2.3 gatsby-plugin-react-helmet: ^3.3.1 => 3.3.1 gatsby-plugin-sharp: ^2.6.4 => 2.6.4 gatsby-plugin-svgr: ^2.0.2 => 2.0.2 gatsby-remark-autolink-headers: ^2.3.2 => 2.3.2 gatsby-remark-copy-linked-files: ^2.3.2 => 2.3.2 gatsby-remark-external-links: 0.0.4 => 0.0.4 gatsby-remark-images: ^3.3.4 => 3.3.4 gatsby-remark-prismjs: ^3.5.1 => 3.5.1 gatsby-source-filesystem: ^2.3.4 => 2.3.4 gatsby-transformer-json: ^2.4.2 => 2.4.2 gatsby-transformer-remark: ^2.8.9 => 2.8.9 gatsby-transformer-sharp: ^2.5.2 => 2.5.2 npmGlobalPackages: gatsby-cli: 2.12.8

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments

Well, I’m coming up on a year of re-upping this issue. And… well, it’s totally my fault.

I just went back to the source file in question, and realized that I forgot to attach a useEffect to update the location on the client. So of course I was seeing the SSR’d value…

For anyone else who comes across this, everything is working as expected. Here’s the solution:

export default function NotFoundPage({location}) {
	const [pathname, setPathname] = useState('');
	useEffect(() => {
		setPathname(location.pathname);
	}, [location]);
	return (
		<main className="not-found">
			<p>Your pathname is {pathname}, and should update client-side.</p>
		</main>
	);
}

This is still an issue.

Sent from my mobile.