Skip to content

Commit

Permalink
chore: cloudfront-function for url-rewrite needed for SPA
Browse files Browse the repository at this point in the history
  • Loading branch information
birme authored and martinstark committed Apr 11, 2024
1 parent d138971 commit 5a798a4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
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

0 comments on commit 5a798a4

Please sign in to comment.