heroBy DigitalOcean

DigitalOcean App Platform: how to redirect all requests to index.html for Single Page Applications

If you are not aware, DigitalOcean now offers their own App Platform which works like Netlify or Vercel if you used those platforms before. If not, essentially you could connect your code repository and then these platforms will take care of the rest e.g. install dependencies, building the project and deploying it somewhere, host it, manage SSL certificates, custom domains, etc.

Everything was quite straightforward, the dev experience is noticeably behind that of the competitors which is a little disappointing to see. The free tier is also more stingy in my opinion. But instead of restricting you to Lambda functions (serverless), you could deploy full blow Node.js (or other languages) backend applications. DigitalOcean charges for each "app" instead of by usage which could end up cheaper if you have a moderately popular application.

The problem

If you have used the competitor platforms and tried to deploy single page application, then you would know if a user tries to go to any path that isn't the root will result in a 404 error.

Why does this happen?

When a user tries to navigate directly (e.g. type into URL or refresh) to domain.com/some-url, the browser will request some-url.html from the server. However, Single Page Application (SPA) runs from index.html file, hence the name. Therefore it does not have the requested file and returns a 404 error.

How come the router library allows us to go to domain.com/some-url?

Routing libraries such as React Router manipulates the browser history to create the effect of multiple path names and pages are available.

The solution

Normally, if we were hosting the SPA ourselves then we'd have to configure Nginx to redirect all traffic to index.html. But what do we do with DigitalOcean?

DigitalOcean doesn't have very clear documentation around this, which could partly be due to the App Platform is still relatively new. I hope this will improve going forward, as this is a pretty fundamental config for any SPA project. After some digging around I found out this is normally done via submitting a config file, which is pretty well documented here. Fortunately, there's an even easier way to do that now. Navigate to your SPA application under Apps.

DigitalOcean App in Nav

Then select the application you wish to make this change to.

DigitalOcean App tabs

Now go to the Settings tab, and scroll down to the bottom. There should be a section that says "Custom Pages". Edit it, input "index.html" and save. Now wait for the redeployment to happen and it should work when you navigate to any paths! 🥳

DigitalOcean App Settings

Buy Me A Coffee