We are having issues trying to make working a SPA with a client router (react router). We are using the concept of have a DOMAIN -> CDN (CloudFront) -> S3
for
When you visit http://mywebsite.com
the request will hit the index.html
file in S3. Then you might click a button and go to http://mywebsite.com/stats
which is an internal route of your React app. Thus, it will not trigger any backend request.
But if you reload the page, http://mywebsite.com/stats
will be sent to S3 as your browser does not know that you are running a React application.
S3 will return 403 error with index.html and Cloudfront will sent you the error.
Solution is using an edge lambda function in cloudfront. Here an example:
const path = require('path')
exports.handler = (evt, ctx, cb) => {
const {request} = evt.Records[0].cf
if (!path.extname(request.uri)) {
request.uri = '/index.html'
}
cb(null, request)
}
Source: https://hackernoon.com/how-to-host-a-single-page-application-with-aws-cloudfront-and-lambda-edge-39ce7b036da2