From e4f42581e694797e4528e0dd6f420b0374b12dff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Birm=C3=A9?= Date: Wed, 10 Apr 2024 21:35:23 +0200 Subject: [PATCH] chore: cloudfront-function for url-rewrite needed for SPA --- aws/cloudfront-functions/README.md | 13 +++++++ aws/cloudfront-functions/url-rewrite-spa.yaml | 39 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 aws/cloudfront-functions/README.md create mode 100644 aws/cloudfront-functions/url-rewrite-spa.yaml diff --git a/aws/cloudfront-functions/README.md b/aws/cloudfront-functions/README.md new file mode 100644 index 00000000..179439a6 --- /dev/null +++ b/aws/cloudfront-functions/README.md @@ -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 +``` diff --git a/aws/cloudfront-functions/url-rewrite-spa.yaml b/aws/cloudfront-functions/url-rewrite-spa.yaml new file mode 100644 index 00000000..08d6cb81 --- /dev/null +++ b/aws/cloudfront-functions/url-rewrite-spa.yaml @@ -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