3

We have a react application hosted/deployed on AWS S3. It uses react-router-dom v6

configuration

When there is an error, I set it to go to index.html. The problem is that when moving like "xxx/admin" within React, there is actually only index.html in s3 (xxx/admin is not present), resulting in an error of 404. After that, when an error occurs, it is redirected to index.html and then called properly.

Please tell me how to get rid of this error. It's hard to find because it's my first aws.


I think before react.js bundle is imported, xxx/main request first and error redirect to index.html. when redirect to index.html, js imported so react will render the correct pages. if so, how do I fix this problem?

or

I think it's SPA, so only one index.html file exists, but when error occurs, AWS s3 called something that doesn't exist file. I want to know the fundamental solution rather than using cloudFront. (redirect error 404 -> 200).

404 not found error

1
  • 1
    I'm not sure about using amazon-S3, but typically you need to configure the server to redirect to your index route where the app is hosted and running, so it can properly route to the correct component in React. Commented Jan 25, 2022 at 18:40

1 Answer 1

18

Disclaimer: this is a solution using CloudFront.

In case it might help.

I encountered similar problems when I used react-router-dom v5 & v6. I used BrowserRouter. I deployed the React app directly to S3 without using AWS Amplify. I kept encountering 403 error instead of 404, although I rechecked all my permission settings.

This article helped me eventually: https://blog.nicera.in/2020/08/hosting-react-app-on-s3-cloudfront-with-react-router-404-fix/. And your questions raised here had been discussed and answered in details in this article.

  1. Open up your CloudFront distribution for the React App. In the top tabs, click on Error Pages.

  2. Add the configurations for 403 & 404 as below.

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your answer, but now i know why this 404 error appears and why i have to use CloudFront configurations. your answer is right! :D
This is a great answer and fixed my issue using react router hosting a single page app on S3 behind a cloudfront distribution. Remember to set both the 404 document settings on the s3 bucket and the 404 doc and response code (change 404 to 200) on the cloudfront distribution.
Important note: using error pages to solve a routing problem, you set CSP and other security headers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.