Categories
deployment frontend typescript

Deploy a Vite React SPA app to CloudFront with working BrowserRouter

When I deployed my websites, then I always had problems with refreshing/sub routes like /finding/latest. Other developers posted solutions like sketchy redirect scripts, but they had a big problem.

These solutions worked, but caused Google SSO to discard the web pages as Page with redirect error.

What is a clean way to deploy a Vite SPA app to Cloudfront?

Setup

  1. Upload build to S3.
  2. In S3, you don’t enable static hosting. Instead, you later set the authorization in cloudfront
  3. In cloudfront, use the Origin access control settings (recommended) authentication to S3 bucket. This means in cloudfront, they give you a policy that you need to add to S3.
  4. add 403 (maybe also 404) error responses that direct to /index.html with 200 response

This will enable clean 200 responses that always redirect to /index.html. Google SEO is happy!

Other issues

index-SUgww9Fu.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.

This should be necessary if you have your deployment in a different folder, but for me it also resolved the MIME type issue. Read more at vite docs

Solution: add to your vite.config.ts

export default defineConfig({
  // depending on your application, base can also be "/"
  base: "/",

Result

You can now add your routes and finally have your SPA app working well with Google SSO. Good luck!