'React App url parameter with S3 and CloudFront

My apologies if the information that I have provided is vague as I am not so experience with AWS and React.

I have a React Application being deployed on S3 and CloudFront as per what is suggested in the following link.

Use S3 and CloudFront to host Static Single Page Apps (SPAs) with HTTPs and www-redirects

So most of the things are working fine. I have 403 and 404 errors being redirected to index.html. However the issue comes in where I have query parameters in my url. eg. https://example.com/example?sample=123 when I enter the url in my browser the query string gets removed from the url. The end result I got is https://example.com/example I have read some articles about forwarding query parameters but it's not working for me.

AWS Documentation - Query String Parameters

Hope I will be able to get some advise here. Thanks in advance.



Solution 1:[1]

The example?sample=123 is redirected to example because S3 sees example?sample=123 as path (a folder named example?sample=123), it will throw 404 as there is no such folder.
As you have mentioned, you have configured 404 -> index.html, the browser then goes back to example, which is very likely the default page of your react app.
Overall it looks like your query string is being cleared, actually it is lost during the redirection.

The solution includes three parts:

  • React
    You can follow these two great tutorials, one for NextJs and another for RCA.
    The way it works is to detect #! in the path, keep and store the query string after redirection.

  • S3
    As included in the two links above, you have to set the redirection rule of the S3 Bucket, to add a #!/ prefix before the path on 403 or 404, it helps React to determine which parts of the url include query string. You can configure it in Properties -> Static website hosting -> Redirection rules – optional. You need to also set index.html as the Index document and enable static web hosting with the correct permission configured.

  • CloudFront

  1. In General, set Default Root Object to index.html, make sure you don't make it as /index.html.
  2. In Origin, set Origin domain to the S3 Static Web Hosting URL (http://[bucket-name].s3-website.[region].amazonaws.com, do not choose the bucket itself.
  3. In Behavior, change Viewer to Redirect HTTP to HTTPS, set Origin request policy - optional to AllViewer to let all query strings go through.

Hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1