Skip to main content

Setup Caddy for SPA Stored at S3 Object Storage. (React with react-router)

· 2 min read
Ajay Dhangar

To set up Caddy for serving a Single Page Application (SPA) like a React app with react-router, you need to handle routing such that all navigation requests are routed to index.html, while also serving the static assets correctly.

Directory Structure on Remote Storage

Let's assume that the React app is stored at a remote storage like S3, minio, etc. The directory structure of the React app on the remote storage should look like this:

Directory Structure
├── index.html
├── static
│ ├── css
│ │ └── main.2d2b7b6a.chunk.css
│ ├── js
│ │ ├── 2.2d2b7b6a.chunk.js
│ │ ├── main.2d2b7b6a.chunk.js
│ │ └── runtime-main.2d2b7b6a.js
│ └── media
│ └── logo.2d2b7b6a.png

Caddyfile Configuration

To serve the React app using Caddy, you need to create a Caddyfile with the following configuration:

Caddyfile
your-domain.com {
root * /path/to/your/react-app
file_server
try_files {path} /index.html
}

In the above configuration:

  • your-domain.com is your domain name.
  • /path/to/your/react-app is the path to your React app on the remote storage.
  • file_server is used to serve the static assets.
  • try_files {path} /index.html is used to route all navigation requests to index.html.

Docker Configuration

If you are using Docker to run Caddy, you can create a Dockerfile with the following configuration:

Dockerfile
FROM caddy:2.4.3

COPY Caddyfile /etc/caddy/Caddyfile

You can then build the Docker image and run the container using the following commands:

Build and Run Docker Container
docker build -t caddy-spa .
docker run -d -p 80:80 caddy-spa

That's it! You have now set up Caddy to serve a Single Page Application (SPA) like a React app with react-router.

Conclusion

In this article, we discussed how to set up Caddy for serving a Single Page Application (SPA) like a React app with react-router. By handling routing and serving static assets correctly, you can ensure that your SPA works as expected when hosted on a remote storage like S3, minio, etc.