Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser back button not working for gatsby.js project

Tags:

browser

gatsby

Anyone know what would cause the back button to not work when using standard Link tags in a gatsby project?

The url changes but the route doesn't update.

This is a gatsby source wordpress project if that helps to know. All wp pages are made with the createPage method, and everything appears to work as expected.

Conversely, I have another gatsby project that does not use the wordpress source. On that project the browser back and forward buttons work fine. So clearly it's not that gatsby itself breaks this by default. But in my inspections I cannot see a fundamental reason why the two projects configurations or anything else would cause this. They're almost identical except the source wordpress part.

Anyone else come across something like this?

like image 597
Kai Qing Avatar asked Dec 21 '25 09:12

Kai Qing


1 Answers

Ok so, for anyone else experiencing this - no doubt your googling has driven you to madness. How can we be the only ones who have dealt with this? Indeed, infuriating.

Fret not, there is a hack. And yeah, I'm sure it's a total hack.

In your gatsby-browser.js file, add this:

exports.onInitialClientRender = () => {
  window.addEventListener('popstate', () =>
    window.location.href = window.location.href
  )
}

WTF is this doing, you ask? It's forcing the url to redirect to itself. Sounds MORONIC, right? It is, except that this only fires when you use the browser's navigation. Problem solved, right? No, not really. Problem is masked. But for me, that is good enough until someone has an actual answer.

Why does this solution suck? Because it breaks the concept of a SPA. You're no longer single page if you force a reload in there. For me, I am not too concerned only because this happens only on back and forward button clicks. But if this were a $50k client, I am positive my little hack wouldn't fly with them.

If anyone has an actual Gatsby solution that doesn't break the SPA model, post it here and I will gladly transfer accepted answer to you. Till then... hack on.

like image 123
Kai Qing Avatar answered Dec 24 '25 04:12

Kai Qing



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!