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.json
and set proper lamdba executionrole
. -
Replace
s3://test.es6.fi/assets/
inpackage.json
with your S3 bucket, e.g.s3://your-bucket/assets/
. -
npm run build
to build front-end code -
npm run deploy
to deploy lambda and upload front build to S3
-
In API Gateway home, click
Create API
-
Choose
New API
and enter someAPI name
, clickCreate API
. -
Choose
Actions -> Create resource
-
Check
Configure as proxy resource
and clickCreate resource
-
In
/{proxy+} - ANY - Setup
, chooseIntegration type
asLambda Function Proxy
, select your lambda's AWS region and enter name of your uploaded lambda function (react-apig-lambda_render-react
if you didn't change name inproject.json
). ClickSave
. -
Choose
Actions -> Deploy API
, setDeployment stage
as[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
assets
directory). ClickCreate
. -
Go to your distribution, navigate to
Behaviors
, clickCreate Behavior
. -
Set
Path Pattern
asassets/*
, choose your S3 origin and clickCreate
. -
In your domain's DNS management interface, point your domain's
CNAME
to your CloudFront distribution.