Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: cloudfront-function for url-rewrite needed for SPA #56

Merged
merged 1 commit into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions aws/cloudfront-functions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# URL rewrite for single page applications (SPAs)

CloudFront Functions event type: viewer request

## Creating the function

```
aws cloudformation deploy \
--region us-east-1 \
--stack-name url-rewrite-stack \
--template-file ./url-rewrite-spa.yaml \
--parameter-overrides AutoPublishParam=true
```
39 changes: 39 additions & 0 deletions aws/cloudfront-functions/url-rewrite-spa.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
AWSTemplateFormatVersion: 2010-09-09
Description: URL rewrite for React Router SPA with client-side routing

Parameters:
AutoPublishParam:
Description: Whether to automatically publish on creation
Type: String
Default: false
AllowedValues:
- true
- false

Resources:
RewriteFunction:
Type: AWS::CloudFront::Function
Properties:
AutoPublish: !Ref AutoPublishParam
FunctionCode: !Sub |
function handler(event) {
var request = event.request;
var uri = request.uri;
var paths = ['assets/', 'img/', '.xml', '.webmanifest', '.js', 'robots.txt']
var isServerPath = (path) => uri.includes(path);

if (!paths.some(isServerPath)) {
request.uri = '/';
}

return request;
}
FunctionConfig:
Comment: "Rewrite the URL for SPAs with client-side routing"
Runtime: cloudfront-js-1.0
Name: !Sub "${AWS::StackName}-rewriteFunction"

Outputs:
FunctionArn:
Description: CloudFront Function
Value: !GetAtt RewriteFunction.FunctionMetadata.FunctionARN
Loading