Single Page Application Refreshing

Single Page Application Refreshing image

- Joshua Ryland, last updated 06-10-2023

When refreshing a SPA you may notice that sometimes it will error or go back to home. This is because React traditional using React Router for example will deliver one html, thus if refreshed or you send a link to someone of the SPA that the server which only has one route, will think it doesn't exist. Thus failing the GET request. React Router handles urls on the client's side, thus doesn't exist if the page hasn't rendered yet.

Solution

Two main ones luckily. Either hash-router/history or catch-all server route.

Hash History

If you do not have access to the server this maybe your only solution. It works by adding a # to the end of your URL root. So www.joshryland.com/contact would become www.joshryland.com/#/contact the browser will ignore everything after the # meaning it will return the home page, but then the React Router will handle the hash and direct to the right page. This is not highly recommended as it can be more resource intensive and creates ugly URLS.

Catch-All Server Route

Ideally you can control the server you are serving from. If you can then you would simply direct all incoming requests to root url or index.html so that React Router can handle for express.js it would look like this.

app.get("/*", function (req, res) {
  res.sendFile(path.join(__dirname, "dist/index.html"), function (err) {
    if (err) {
      res.status(500).send(err);
    }
  });
});

Here you can also optimize for SEO by sending back the html for specific routes so they are server-side rended and thus tags can be picked up by search engines.

Related: