Render React.js on-demand with CDN caching.
Minimal example on how to render React & React Router v4 with Amazon API Gateway, AWS Lambda and CloudFront.
Basic example app from React Router documentation. Initial server-side render and acts as SPA from there.
-
Edit
project.jsonand set proper lamdba executionrole. -
Replace
s3://test.es6.fi/assets/inpackage.jsonwith your S3 bucket, e.g.s3://your-bucket/assets/. -
npm run buildto build front-end code -
npm run deployto deploy lambda and upload front build to S3
-
In API Gateway home, click
Create API -
Choose
New APIand enter someAPI name, clickCreate API. -
Choose
Actions -> Create resource -
Check
Configure as proxy resourceand clickCreate resource -
In
/{proxy+} - ANY - Setup, chooseIntegration typeasLambda Function Proxy, select your lambda's AWS region and enter name of your uploaded lambda function (react-apig-lambda_render-reactif you didn't change name inproject.json). ClickSave. -
Choose
Actions -> Deploy API, setDeployment stageas[New Stage], enter stage name and clickDeploy -
Now you should be able to invoke the lambda renderer by navigating to
https://your-invoke-url/your-stage-name/index
-
Create distribution, paste your API Gateway url as
Origin domain name, e.g.https://your-invoke-url/your-stage-name/index. Make sure to include/index. -
Set your custom domain in
Alternate Domain Names (CNAMEs) -
You can leave other settings as they are if you don't want to customize anything, click
Create distribution. -
Go to your distribution, navigate to
Origins, clickCreate origin -
Choose your S3 bucket (you should create it now if you haven't already. Make sure there's
assetsdirectory). ClickCreate. -
Go to your distribution, navigate to
Behaviors, clickCreate Behavior. -
Set
Path Patternasassets/*, choose your S3 origin and clickCreate. -
In your domain's DNS management interface, point your domain's
CNAMEto your CloudFront distribution.