close

Serve React website with Page Routing from Caddy

Configuring caddy to serve react app which is using react-router-dom to navigate from different pages in a website

With default caddy fileserver configuration if you serve a react website which has its own routing for different views. You might find that its resulting in 404 error or views not rendering properly.

It happens because caddy can’t find any resource to respond with, for that path like /about. But because React is a Single Page App and there is only one index.html file, after that react handles the rendering of views according to different paths.

So to fix that we need to configure our webserver in such a way that for every path if there is not a static file to respond with then send the index.html

In caddy you can do this by using try_files directive.

:80

root * /srv
try_files {path} /index.html
file_server

Now caddy will respond with index.html for different paths, after that react will take over and render a page for that path.