├── .env
├── .gitignore
├── .prettierrc
├── CODE_OF_CONDUCT.md
├── LICENSE.md
├── README.md
├── aws
├── buildspecs
│ ├── assets.yml
│ ├── cdk.yml
│ ├── release.yml
│ └── render.yml
├── index.ts
├── lib
│ └── helpers.ts
├── overview.png
└── stacks
│ ├── domain.ts
│ ├── pipeline.ts
│ └── render.ts
├── cdk.json
├── config.ts
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── server
├── config.ts
├── handler
│ ├── lambda.ts
│ └── local.ts
├── lib
│ └── render.tsx
└── router.ts
├── src
├── App.tsx
├── components
│ ├── Footer.tsx
│ └── Navigation.tsx
├── index.tsx
├── pages
│ ├── Details.tsx
│ ├── Error.tsx
│ └── Home.tsx
├── react-app-env.d.ts
├── serviceWorker.ts
└── setupTests.ts
├── tsconfig.cdk.json
├── tsconfig.json
├── tsconfig.server.json
└── yarn.lock
/.env:
--------------------------------------------------------------------------------
1 | REACT_APP_NAME=cra-serverless
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | /node_modules
3 | /build
4 | .server
5 |
6 | #cdk
7 | /dist
8 | /cdk.out
9 | /cdk.context.json
10 |
11 | # misc
12 | .DS_Store
13 | .env.local
14 | .env.development.local
15 | .env.test.local
16 | .env.production.local
17 |
18 | npm-debug.log*
19 | yarn-debug.log*
20 | yarn-error.log*
21 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "semi": false,
3 | "singleQuote": true,
4 | "printWidth": 100,
5 | "tabWidth": 2,
6 | "trailingComma": "all"
7 | }
8 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | - Using welcoming and inclusive language
12 | - Being respectful of differing viewpoints and experiences
13 | - Gracefully accepting constructive criticism
14 | - Focusing on what is best for the community
15 | - Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | - Trolling, insulting/derogatory comments, and personal or political attacks
21 | - Public or private harassment
22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | - Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting our team at **code@sbstjn.com**. As an alternative feel free to reach out to any of us personally. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | ### MIT License
2 |
3 | Copyright (c) 2020 Sebastian Müller
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Serverless SSR for [create-react-app][cra]
2 |
3 | [](https://github.com/sbstjn/cra-serverless/blob/master/LICENSE.md)
4 | [](https://sbstjn.com/serverless-create-react-app-server-side-rendering-ssr-lamda.html)
5 | [](https://superluminar.io/2020/02/07/react-spa-und-server-side-rendering-ssr-mit-aws-lambda-cloudfront-und-dem-cdk/)
6 |
7 | > Full-featured AWS architecture to use [**Server-Side Rendering**][ssr] for any [**create-react-app**][cra] project using **Lambda**, **API Gateway**, **CloudFront**. All infrastructure is configured using the [**AWS Cloud Development Kit**][cdk] and can be deployed using [**AWS CodePipeline**][pipeline] and [**AWS CodeBuild**][codebuild].
8 | >
9 | > Have fun, and be a nice **anti-fascist** human being!
10 | >
11 | > https://d31tuk9nqnnpkk.cloudfront.net/
12 | >
13 | > **Guide (EN):** [React with server-side rendering on AWS Lambda](https://sbstjn.com/serverless-create-react-app-server-side-rendering-ssr-lamda.html) on [sbstjn.com](https://sbstjn.com) \
14 | > **Guide (DE):** [React und server-side rendering mit AWS Lambda und CloudFront](https://superluminar.io/2020/02/07/react-spa-und-server-side-rendering-ssr-mit-aws-lambda-cloudfront-und-dem-cdk/) on [superluminar.io](https://superluminar.io)
15 |
16 | Whenever you search for **server-side rendering** of React applications, you will read it's hard to accomplish. **But why?** Most probably, you'll end up with frameworks like [razzle](https://github.com/jaredpalmer/razzle) or [Next.js](https://nextjs.org/) only because you wanted a little bit of pre-rendered HTML for your React application.
17 |
18 | The idea of **cra-serverless** is pretty simple: Use your existing, un-ejected, and unpatched [**create-react-app**][cra] and replace **`BrowserRouter`** with **`StaticRouter`**, deploy it to [**AWS Lambda**][lambda], and finally put a CDN in front of it. You'll have your same React SPA, but now you can have pre-rendered HTML content for all routes in your application. This even works fine with frameworks like [**styled-components**][sc] or [**apollo client**][apollo] for using [**GraphQL on AppSync**][appsync].
19 |
20 | 
21 |
22 | Yes, this is **serverless server-side rendering**, so let's call it **serverless pre-rendering for React**. 🤯
23 |
24 | ##### Extended Guides:
25 |
26 | - [React with server-side rendering on AWS Lambda](https://sbstjn.com/serverless-create-react-app-server-side-rendering-ssr-lamda.html) (**English**)
27 | - [React und server-side rendering mit AWS Lambda und CloudFront](https://superluminar.io/2020/02/07/react-spa-und-server-side-rendering-ssr-mit-aws-lambda-cloudfront-und-dem-cdk/) (**German**)
28 |
29 | ## Architecture
30 |
31 | - **TypeScript**, for God's sake
32 | - Basic **un-ejected** [create-react-app][cra] stored `./src`
33 | - **SSR** using `react-dom/server` and [koa][koa] in `./server`
34 | - **Infrastructure as Code** using [AWS Cloud Development Kit][cdk] in `./aws`
35 | - [AWS Lambda][lambda] for server-side (pre-)rendering of **React SPA**
36 | - [Amazon CloudFront][cloudfront] to **cache pre-rendered HTML** and serve assets from S3
37 | - [AWS CodePipeline][pipeline] and [AWS CodeBuild][codebuild] for **Continious Deployments**
38 |
39 | ## Usage
40 |
41 | The primary goal for [cra-serverless](https://github.com/sbstjn/cra-serverless) is to use a default [create-react-app][cra] setup without any changes and avoid to eject it from react-scripts.
42 |
43 | ```bash
44 | # Start your local environment as always
45 | $ > yarn start
46 |
47 | # Build your static SPA as always
48 | $ > yarn build
49 | ```
50 |
51 | You can develop and build SPA with the usual flow. Afterwards, you can run a local HTTP server with [koa][koa] to test-drive your server-side rendering. The built project is intended to be uploaded to AWS Lambda, but you can deploy the Node.js application to other services as well.
52 |
53 | ```bash
54 | # Start local server-side rendering service
55 | $ > yarn run:local
56 |
57 | # Build Node.js service for server-side rendering
58 | $ > yarn build:server
59 | ```
60 |
61 | All full-featured pipeline using AWS CodePipeline and AWS CodeBuild using the [AWS Cloud Development Kit][cdk] is included to [support continious deployments](#deployments-and-configuration). (*Jump to [Deployments and Configuration](#deployments-and-configuration)*)
62 |
63 | ## How it Works - In a Nutshell
64 |
65 | Most React applications use the `react-router-dom` with `BrowserRouter` :
66 |
67 | ```tsx
68 | import React from 'react'
69 | import { BrowserRouter } from 'react-router-dom'
70 |
71 | React.render(
72 |
73 |
74 | ,
75 | document.getElementById('root'),
76 | )
77 | ```
78 |
79 | Lucky us, a `StaticRouter` exists as well and `react-dom` has a function called `renderToString` :
80 |
81 | ```typescript
82 | import { renderToString } from 'react-dom/server'
83 | import { StaticRouter } from 'react-router-dom'
84 |
85 | const markup = renderToString(
86 |
87 |
88 | ,
89 | )
90 | ```
91 |
92 | Next, the value of `markup` will be injected into your `index.html` file and that's it. In a Nutshell, [**cra-serverless**][cra-serverless] uses existing features of the frameworks you already use and wraps them in a serverless architecture with AWS Lambda.
93 |
94 | ## Deployments and Configuration
95 |
96 | Based on [cra-pipeline][cra-pipeline], all you need is a [personal GitHub Access Token][token] and your own fork of this repository. If you have both things in place, store the token in [AWS Systems Manager][sm]:
97 |
98 | ```bash
99 | $ > aws secretsmanager create-secret \
100 | --name GitHubToken \
101 | --secret-string abcdefg1234abcdefg56789abcdefg \
102 | --region us-east-1
103 |
104 | {
105 | "ARN": "arn:aws:secretsmanager:us-east-1:123456789001:secret:GitHubToken-uNBxTr",
106 | "Name": "GitHubToken",
107 | "VersionId": "4acda3d1-877f-4032-b38e-17bc50239883"
108 | }
109 | ```
110 |
111 | As everything is configured using [AWS Cloud Development Kit][cdk], you need to prepare (_aka bootstrap_) your AWS account once for the usage of the **CDK** in your desired AWS region:
112 |
113 | ```bash
114 | $ > yarn cdk bootstrap --region us-east-1
115 |
116 | ⏳ Bootstrapping environment aws://123456789001/us-east-1...
117 |
118 | 0/2 | 5:06:49 PM | CREATE_IN_PROGRESS | AWS::S3::Bucket | StagingBucket
119 | 0/2 | 5:06:50 PM | CREATE_IN_PROGRESS | AWS::S3::Bucket | StagingBucket Resource creation Initiated
120 | 1/2 | 5:07:11 PM | CREATE_COMPLETE | AWS::S3::Bucket | StagingBucket
121 |
122 | ✅ Environment aws://123456789001/us-east-1 bootstrapped.
123 | ```
124 |
125 | Next, have a look at the `./config.ts` file in the root folder and configure at least the `github` section of the file.
126 |
127 | ```typescript
128 | export const config = {
129 | name: 'cra-serverless',
130 | github: {
131 | owner: 'sbstjn',
132 | repository: 'cra-serverless',
133 | },
134 | env: { region: 'us-east-1' },
135 | }
136 | ```
137 |
138 | After changing the GitHub repository information, just deploy the CloudFormation stack for the included [AWS CodePipeline][pipeline] and all resources will be created for you.
139 |
140 | ```bash
141 | $ > yarn cdk deploy cra-serverless-pipeline
142 |
143 | Pipeline: deploying...
144 | Pipeline: creating CloudFormation changeset...
145 |
146 | ✅ Pipeline
147 | ```
148 |
149 | Head over to the [AWS Management Console][console] and watch the beauty of a deploy pipeline and CloudFormation stacks. All resources will be created for you, and after a while a [CloudFront Distribution][cloudfront] is available for the included example application.
150 |
151 | ## Further Reading
152 |
153 | - [**sbstjn.com**](https://sbstjn.com) for a detailed guide in English
154 | - [**superluminar.io**](https://superluminar.io) for a detailed guide in German
155 |
156 | ## License
157 |
158 | Feel free to use the code, it's released using the [MIT license](LICENSE.md).
159 |
160 | ## Contribution
161 |
162 | You are welcome to contribute to this project! 😘
163 |
164 | To make sure you have a pleasant experience, please read the [code of conduct](CODE_OF_CONDUCT.md). It outlines core values and beliefs and will make working together a happier experience.
165 |
166 | [cloudfront]: https://aws.amazon.com/cloudfront/
167 | [console]: https://aws.amazon.com/console/
168 | [sm]: https://aws.amazon.com/systems-manager/
169 | [token]: https://github.com/settings/tokens
170 | [cra-pipeline]: https://github.com/sbstjn/cra-pipeline
171 | [cra-serverless]: https://github.com/sbstjn/cra-serverless
172 | [lambda]: https://aws.amazon.com/lambda/
173 | [appsync]: https://aws.amazon.com/appsync/
174 | [apollo]: https://www.apollographql.com/docs/react/
175 | [sc]: https://styled-components.com
176 | [cra]: https://create-react-app.dev/
177 | [ssr]: https://reactjs.org/docs/react-dom-server.html
178 | [cdk]: https://docs.aws.amazon.com/cdk/latest/guide/home.html
179 | [koa]: https://koajs.com/
180 | [codebuild]: https://aws.amazon.com/codebuild/
181 | [pipeline]: https://aws.amazon.com/codepipeline/
182 |
--------------------------------------------------------------------------------
/aws/buildspecs/assets.yml:
--------------------------------------------------------------------------------
1 | version: 0.2
2 |
3 | phases:
4 | install:
5 | runtime-versions:
6 | nodejs: 12
7 | commands:
8 | - yarn install
9 | build:
10 | commands:
11 | - yarn build
12 |
13 | artifacts:
14 | base-directory: build
15 | files:
16 | - '**/*'
17 |
18 | cache:
19 | paths:
20 | - 'node_modules/**/*'
21 |
--------------------------------------------------------------------------------
/aws/buildspecs/cdk.yml:
--------------------------------------------------------------------------------
1 | version: 0.2
2 |
3 | phases:
4 | install:
5 | runtime-versions:
6 | nodejs: 12
7 | commands:
8 | - yarn install
9 | build:
10 | commands:
11 | - yarn cdk synth
12 |
13 | artifacts:
14 | base-directory: cdk.out
15 | files:
16 | - '**/*'
17 |
18 | cache:
19 | paths:
20 | - 'node_modules/**/*'
21 |
--------------------------------------------------------------------------------
/aws/buildspecs/release.yml:
--------------------------------------------------------------------------------
1 | version: 0.2
2 |
3 | phases:
4 | install:
5 | runtime-versions:
6 | nodejs: 12
7 | build:
8 | commands:
9 | - export DISTRIBUTION_ID=`aws ssm get-parameter --name "/$SSM_NAMESPACE/CloudFront/DistributionID" --query "Parameter.Value" --output text`
10 | - yarn cdn:invalidate
11 |
--------------------------------------------------------------------------------
/aws/buildspecs/render.yml:
--------------------------------------------------------------------------------
1 | version: 0.2
2 |
3 | phases:
4 | install:
5 | runtime-versions:
6 | nodejs: 12
7 | commands:
8 | - yarn install
9 | build:
10 | commands:
11 | - mkdir .server
12 | - cp -rfv $CODEBUILD_SRC_DIR_assets ./build
13 | - yarn build:server
14 | - yarn package:server
15 |
16 | artifacts:
17 | base-directory: .server
18 | files:
19 | - '**/*'
20 |
21 | cache:
22 | paths:
23 | - 'node_modules/**/*'
24 |
--------------------------------------------------------------------------------
/aws/index.ts:
--------------------------------------------------------------------------------
1 | import * as cdk from '@aws-cdk/core'
2 |
3 | import { config } from '../config'
4 | import { DomainStack } from './stacks/domain'
5 | import { RenderStack } from './stacks/render'
6 | import { PipelineStack } from './stacks/pipeline'
7 |
8 | const name = config.name
9 | const app = new cdk.App()
10 |
11 | const render = new RenderStack(app, `${name}-render`, config)
12 | new DomainStack(app, `${name}-domain`, config)
13 | new PipelineStack(app, `${name}-pipeline`, { ...config, code: render.code })
14 |
15 | app.synth()
16 |
--------------------------------------------------------------------------------
/aws/lib/helpers.ts:
--------------------------------------------------------------------------------
1 | import * as SSM from '@aws-cdk/aws-ssm'
2 | import * as CDK from '@aws-cdk/core'
3 |
4 | export const getParam = (scope: CDK.Construct, name: string) => {
5 | return SSM.StringParameter.valueForStringParameter(scope, name)
6 | }
7 |
--------------------------------------------------------------------------------
/aws/overview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sbstjn/cra-serverless/94c0c8904ec8452e45a9e055f7f1eeee3f861b4d/aws/overview.png
--------------------------------------------------------------------------------
/aws/stacks/domain.ts:
--------------------------------------------------------------------------------
1 | import * as CloudFront from '@aws-cdk/aws-cloudfront'
2 | import * as S3 from '@aws-cdk/aws-s3'
3 | import * as SSM from '@aws-cdk/aws-ssm'
4 | import * as CDK from '@aws-cdk/core'
5 |
6 | import { getParam } from '../lib/helpers'
7 |
8 | export interface DomainProps extends CDK.StackProps {
9 | name: string
10 | }
11 |
12 | export class DomainStack extends CDK.Stack {
13 | constructor(app: CDK.App, id: string, props: DomainProps) {
14 | super(app, id, props)
15 |
16 | const apiID = getParam(this, `/${props.name}/APIGateway/ApiId`)
17 | const apiDomainName = `${apiID}.execute-api.${this.region}.amazonaws.com`
18 |
19 | const assetsBucket = S3.Bucket.fromBucketAttributes(this, 'AssetsBucket', {
20 | bucketName: getParam(this, `/${props.name}/S3/Assets/Name`),
21 | bucketDomainName: getParam(this, `/${props.name}/S3/Assets/DomainName`),
22 | })
23 |
24 | const distribution = new CloudFront.CloudFrontWebDistribution(this, 'CDN', {
25 | httpVersion: CloudFront.HttpVersion.HTTP2,
26 | priceClass: CloudFront.PriceClass.PRICE_CLASS_100,
27 | viewerProtocolPolicy: CloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
28 | defaultRootObject: '/',
29 | originConfigs: [
30 | {
31 | s3OriginSource: {
32 | s3BucketSource: assetsBucket,
33 | },
34 | behaviors: [
35 | {
36 | allowedMethods: CloudFront.CloudFrontAllowedMethods.GET_HEAD_OPTIONS,
37 | compress: true,
38 | pathPattern: '/*.*',
39 | forwardedValues: {
40 | queryString: false,
41 | cookies: { forward: 'none' },
42 | },
43 | },
44 | ],
45 | },
46 | {
47 | originPath: '/prod',
48 | customOriginSource: {
49 | domainName: apiDomainName,
50 | originProtocolPolicy: CloudFront.OriginProtocolPolicy.HTTPS_ONLY,
51 | },
52 | behaviors: [
53 | {
54 | allowedMethods: CloudFront.CloudFrontAllowedMethods.ALL,
55 | compress: true,
56 | isDefaultBehavior: true,
57 | forwardedValues: {
58 | queryString: true,
59 | cookies: { forward: 'all' },
60 | },
61 | },
62 | ],
63 | },
64 | ],
65 | })
66 |
67 | new SSM.StringParameter(this, 'SSMCloudFrontDomainName', {
68 | description: 'CloudFront DomainName',
69 | parameterName: `/${props.name}/CloudFront/DomainName`,
70 | stringValue: distribution.domainName,
71 | })
72 |
73 | new SSM.StringParameter(this, 'SSMCloudFrontDistributionID', {
74 | description: 'CloudFront DistributionID',
75 | parameterName: `/${props.name}/CloudFront/DistributionID`,
76 | stringValue: distribution.distributionId,
77 | })
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/aws/stacks/pipeline.ts:
--------------------------------------------------------------------------------
1 | import * as CodeBuild from '@aws-cdk/aws-codebuild'
2 | import * as CodePipeline from '@aws-cdk/aws-codepipeline'
3 | import * as CodePipelineAction from '@aws-cdk/aws-codepipeline-actions'
4 | import * as IAM from '@aws-cdk/aws-iam'
5 | import * as Lambda from '@aws-cdk/aws-lambda'
6 | import * as S3 from '@aws-cdk/aws-s3'
7 | import * as SSM from '@aws-cdk/aws-ssm'
8 | import * as CDK from '@aws-cdk/core'
9 |
10 | export interface PipelineProps extends CDK.StackProps {
11 | name: string
12 | github: {
13 | owner: string
14 | repository: string
15 | }
16 |
17 | code: Lambda.CfnParametersCode
18 | }
19 |
20 | export class PipelineStack extends CDK.Stack {
21 | constructor(scope: CDK.App, id: string, props: PipelineProps) {
22 | super(scope, id, props)
23 |
24 | // Amazon S3 bucket to store CRA website
25 | const bucketAssets = new S3.Bucket(this, 'Files', {
26 | websiteIndexDocument: 'index.html',
27 | publicReadAccess: true,
28 | })
29 |
30 | // Store S3 Bucket Name in Parameter Store
31 | new SSM.StringParameter(this, 'SSMBucketAssetsName', {
32 | description: 'S3 Bucket Name for Assets',
33 | parameterName: `/${props.name}/S3/Assets/Name`,
34 | stringValue: bucketAssets.bucketName,
35 | })
36 |
37 | // Store S3 DomainName Name in Parameter Store
38 | new SSM.StringParameter(this, 'SSMBucketAssetsDomainName', {
39 | description: 'S3 Bucket DomainName for Assets',
40 | parameterName: `/${props.name}/S3/Assets/DomainName`,
41 | stringValue: bucketAssets.bucketDomainName,
42 | })
43 |
44 | // Initialize named artifacts for AWS CodePipeline and AWS CodeBuild
45 | const outputSources = new CodePipeline.Artifact('sources')
46 | const outputAssets = new CodePipeline.Artifact('assets')
47 | const outputRender = new CodePipeline.Artifact('render')
48 | const outputCDK = new CodePipeline.Artifact('cdk')
49 |
50 | // Create AWS CodePipeline Pipeline
51 | const pipeline = new CodePipeline.Pipeline(this, 'Pipeline', {
52 | pipelineName: props.name,
53 | restartExecutionOnUpdate: false,
54 | })
55 |
56 | // AWS CodePipeline stage to clone sources from GitHub repository
57 | pipeline.addStage({
58 | stageName: 'Sources',
59 | actions: [
60 | new CodePipelineAction.GitHubSourceAction({
61 | actionName: 'Checkout',
62 | owner: props.github.owner,
63 | repo: props.github.repository,
64 | oauthToken: CDK.SecretValue.secretsManager('GitHubToken'),
65 | output: outputSources, // Store files in artifact
66 | trigger: CodePipelineAction.GitHubTrigger.WEBHOOK,
67 | }),
68 | ],
69 | })
70 |
71 | // AWS CodePipeline stage to build CRA website and CDK resources
72 | pipeline.addStage({
73 | stageName: 'Build',
74 | actions: [
75 | new CodePipelineAction.CodeBuildAction({
76 | actionName: 'CDK',
77 | project: new CodeBuild.PipelineProject(this, 'BuildCDK', {
78 | projectName: 'CDK',
79 | buildSpec: CodeBuild.BuildSpec.fromSourceFilename('./aws/buildspecs/cdk.yml'),
80 | }),
81 | input: outputSources, // Restore files from artifact
82 | outputs: [outputCDK], // Store files in artifact
83 | runOrder: 10,
84 | }),
85 | new CodePipelineAction.CodeBuildAction({
86 | actionName: 'Assets',
87 | project: new CodeBuild.PipelineProject(this, 'BuildAssets', {
88 | projectName: 'Assets',
89 | buildSpec: CodeBuild.BuildSpec.fromSourceFilename('./aws/buildspecs/assets.yml'),
90 | }),
91 | input: outputSources, // Restore files from artifact
92 | outputs: [outputAssets], // Store files in artifact
93 | environmentVariables: {
94 | REACT_APP_NAME: { value: props.name },
95 | },
96 | runOrder: 10,
97 | }),
98 | new CodePipelineAction.CodeBuildAction({
99 | actionName: 'Render',
100 | project: new CodeBuild.PipelineProject(this, 'BuildRender', {
101 | projectName: 'Render',
102 | buildSpec: CodeBuild.BuildSpec.fromSourceFilename('./aws/buildspecs/render.yml'),
103 | }),
104 | input: outputSources, // Restore files from artifact
105 | outputs: [outputRender], // Store files in artifact
106 | extraInputs: [outputAssets], // Restore additional files from artifact
107 | runOrder: 20,
108 | }),
109 | ],
110 | })
111 |
112 | // AWS CodePipeline stage to deploy static files to S3, update SSR code in AWS Lambda, and ensure CloudFront CDN
113 | pipeline.addStage({
114 | stageName: 'Deploy',
115 | actions: [
116 | new CodePipelineAction.S3DeployAction({
117 | actionName: 'Assets',
118 | input: outputAssets,
119 | bucket: bucketAssets,
120 | runOrder: 10,
121 | }),
122 | new CodePipelineAction.CloudFormationCreateUpdateStackAction({
123 | actionName: 'Render',
124 | templatePath: outputCDK.atPath(`${props.name}-render.template.json`),
125 | stackName: `${props.name}-render`,
126 | adminPermissions: true,
127 | parameterOverrides: {
128 | ...props.code.assign(outputRender.s3Location),
129 | },
130 | runOrder: 20,
131 | extraInputs: [outputRender],
132 | }),
133 | new CodePipelineAction.CloudFormationCreateUpdateStackAction({
134 | actionName: 'Domain',
135 | templatePath: outputCDK.atPath(`${props.name}-domain.template.json`),
136 | stackName: `${props.name}-domain`,
137 | adminPermissions: true,
138 | runOrder: 50,
139 | }),
140 | ],
141 | })
142 |
143 | // Custom IAM Role to access SSM Parameter Store and invalidate CloudFront Distribution
144 | const roleRelease = new IAM.Role(this, 'ReleaseCDNRole', {
145 | assumedBy: new IAM.ServicePrincipal('codebuild.amazonaws.com'),
146 | path: '/',
147 | })
148 |
149 | roleRelease.addToPolicy(
150 | new IAM.PolicyStatement({
151 | actions: ['ssm:GetParameter'],
152 | resources: [`arn:aws:ssm:${this.region}:${this.account}:parameter/${props.name}/*`],
153 | effect: IAM.Effect.ALLOW,
154 | }),
155 | )
156 |
157 | roleRelease.addToPolicy(
158 | new IAM.PolicyStatement({
159 | actions: ['cloudfront:CreateInvalidation'],
160 | resources: [`arn:aws:cloudfront::${this.account}:distribution/*`],
161 | effect: IAM.Effect.ALLOW,
162 | }),
163 | )
164 |
165 | // AWS CodePipeline stage to release new static files and invalidate CloudFront distribution
166 | pipeline.addStage({
167 | stageName: 'Release',
168 | actions: [
169 | new CodePipelineAction.CodeBuildAction({
170 | actionName: 'CDN',
171 | project: new CodeBuild.PipelineProject(this, 'ReleaseCDN', {
172 | projectName: 'CDN',
173 | role: roleRelease,
174 | environmentVariables: {
175 | SSM_NAMESPACE: { value: props.name },
176 | },
177 | buildSpec: CodeBuild.BuildSpec.fromSourceFilename('./aws/buildspecs/release.yml'),
178 | }),
179 | input: outputSources,
180 | }),
181 | ],
182 | })
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/aws/stacks/render.ts:
--------------------------------------------------------------------------------
1 | import * as APIGateway from '@aws-cdk/aws-apigateway'
2 | import * as Lambda from '@aws-cdk/aws-lambda'
3 | import * as SSM from '@aws-cdk/aws-ssm'
4 | import * as CDK from '@aws-cdk/core'
5 |
6 | export interface RenderProps extends CDK.StackProps {
7 | name: string
8 | }
9 |
10 | export class RenderStack extends CDK.Stack {
11 | public readonly code: Lambda.CfnParametersCode
12 |
13 | constructor(app: CDK.App, id: string, props: RenderProps) {
14 | super(app, id, props)
15 |
16 | this.code = Lambda.Code.cfnParameters({
17 | bucketNameParam: new CDK.CfnParameter(this, 'CodeBucketName'),
18 | objectKeyParam: new CDK.CfnParameter(this, 'CodeBucketObjectKey'),
19 | })
20 |
21 | const render = new Lambda.Function(this, 'Render', {
22 | code: this.code,
23 | handler: 'server/handler/lambda.run',
24 | runtime: Lambda.Runtime.NODEJS_12_X,
25 | memorySize: 1024,
26 | timeout: CDK.Duration.seconds(3),
27 | })
28 |
29 | const api = new APIGateway.RestApi(this, 'API')
30 | const integration = new APIGateway.LambdaIntegration(render)
31 |
32 | const root = api.root
33 | const path = api.root.addResource('{proxy+}')
34 |
35 | root.addMethod('ANY', integration)
36 | path.addMethod('ANY', integration)
37 |
38 | new SSM.StringParameter(this, 'SSMAPIGatewayRestIs', {
39 | description: 'API Gateway ID',
40 | parameterName: `/${props.name}/APIGateway/ApiId`,
41 | stringValue: api.restApiId,
42 | })
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/cdk.json:
--------------------------------------------------------------------------------
1 | {
2 | "app": "npx ts-node --project tsconfig.cdk.json aws"
3 | }
4 |
--------------------------------------------------------------------------------
/config.ts:
--------------------------------------------------------------------------------
1 | export const config = {
2 | name: 'cra-serverless',
3 | github: {
4 | owner: 'sbstjn',
5 | repository: 'cra-serverless',
6 | },
7 | env: { region: 'us-east-1' },
8 | }
9 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cra-serverless",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "koa": "^2.11.0",
7 | "koa-route": "^3.2.0",
8 | "koa-router": "^8.0.6",
9 | "koa-static": "^5.0.0",
10 | "react": "^16.12.0",
11 | "react-dom": "^16.12.0",
12 | "react-helmet-async": "^1.0.4",
13 | "react-router": "^5.1.2",
14 | "react-router-dom": "^5.1.2",
15 | "serverless-http": "^2.3.1",
16 | "styled-components": "^5.0.0"
17 | },
18 | "scripts": {
19 | "start": "react-scripts start",
20 | "build": "react-scripts build",
21 | "test": "react-scripts test",
22 | "eject": "react-scripts eject",
23 | "clean:server": "rimraf .server",
24 | "run:local": "npx ts-node --project tsconfig.server.json server/handler/local.ts",
25 | "build:server": "tsc --project tsconfig.server.json",
26 | "cdn:invalidate": "aws cloudfront create-invalidation --distribution-id $DISTRIBUTION_ID --paths \"/*\"",
27 | "package:server": "cp -rf build .server/build; yarn install --prod --silent --no-lockfile --non-interactive --modules-folder .server/node_modules",
28 | "cdk": "cdk"
29 | },
30 | "eslintConfig": {
31 | "extends": "react-app"
32 | },
33 | "browserslist": {
34 | "production": [
35 | ">0.2%",
36 | "not dead",
37 | "not op_mini all"
38 | ],
39 | "development": [
40 | "last 1 chrome version",
41 | "last 1 firefox version",
42 | "last 1 safari version"
43 | ]
44 | },
45 | "devDependencies": {
46 | "@aws-cdk/aws-apigateway": "^1.22.0",
47 | "@aws-cdk/aws-certificatemanager": "^1.22.0",
48 | "@aws-cdk/aws-cloudfront": "^1.22.0",
49 | "@aws-cdk/aws-codebuild": "^1.22.0",
50 | "@aws-cdk/aws-codedeploy": "^1.22.0",
51 | "@aws-cdk/aws-codepipeline": "^1.22.0",
52 | "@aws-cdk/aws-codepipeline-actions": "^1.22.0",
53 | "@aws-cdk/aws-lambda": "^1.22.0",
54 | "@aws-cdk/aws-route53": "^1.22.0",
55 | "@aws-cdk/aws-route53-targets": "^1.22.0",
56 | "@aws-cdk/aws-s3": "^1.22.0",
57 | "@aws-cdk/aws-ssm": "^1.22.0",
58 | "@aws-cdk/core": "^1.22.0",
59 | "@testing-library/jest-dom": "^4.2.4",
60 | "@testing-library/react": "^9.3.2",
61 | "@testing-library/user-event": "^7.1.2",
62 | "@types/jest": "^24.0.0",
63 | "@types/koa-route": "^3.2.4",
64 | "@types/koa-static": "^4.0.1",
65 | "@types/node": "^12.0.0",
66 | "@types/react": "^16.9.0",
67 | "@types/react-dom": "^16.9.0",
68 | "@types/react-helmet": "^5.0.15",
69 | "@types/react-router": "^5.1.4",
70 | "@types/react-router-dom": "^5.1.3",
71 | "@types/styled-components": "^4.4.2",
72 | "aws-cdk": "^1.22.0",
73 | "react-scripts": "3.3.0",
74 | "rimraf": "^3.0.1",
75 | "ts-node": "^8.6.2",
76 | "typescript": "~3.7.2"
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sbstjn/cra-serverless/94c0c8904ec8452e45a9e055f7f1eeee3f861b4d/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sbstjn/cra-serverless/94c0c8904ec8452e45a9e055f7f1eeee3f861b4d/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sbstjn/cra-serverless/94c0c8904ec8452e45a9e055f7f1eeee3f861b4d/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 |
--------------------------------------------------------------------------------
/server/config.ts:
--------------------------------------------------------------------------------
1 | import { resolve } from 'path'
2 |
3 | const assets = resolve(__dirname, '../build')
4 |
5 | export const paths = { assets }
6 | export const files = { index: resolve(assets, 'index.html') }
7 |
--------------------------------------------------------------------------------
/server/handler/lambda.ts:
--------------------------------------------------------------------------------
1 | import { Router } from '../router'
2 |
3 | import serverless from 'serverless-http'
4 |
5 | export const run = serverless(Router)
6 |
--------------------------------------------------------------------------------
/server/handler/local.ts:
--------------------------------------------------------------------------------
1 | import { Router } from '../router'
2 |
3 | const port = process.env.PORT || 3000
4 |
5 | console.log(`\n🎉 Starting HTTP server at http://localhost:${port}`)
6 |
7 | Router.listen(port)
8 |
--------------------------------------------------------------------------------
/server/lib/render.tsx:
--------------------------------------------------------------------------------
1 | import { readFileSync } from 'fs'
2 | import React from 'react'
3 | import { renderToString } from 'react-dom/server'
4 | import { HelmetData } from 'react-helmet'
5 | import { HelmetProvider } from 'react-helmet-async'
6 | import { StaticRouter } from 'react-router-dom'
7 | import { ServerStyleSheet } from 'styled-components'
8 |
9 | import { files } from '../config'
10 | const html = readFileSync(files.index).toString()
11 |
12 | export const render = (Tree: React.ElementType, path: string) => {
13 | const context = { helmet: {} as HelmetData }
14 | const sheets = new ServerStyleSheet()
15 |
16 | const markup = renderToString(
17 | sheets.collectStyles(
18 |
19 |
20 |
21 |
22 | ,
23 | ),
24 | )
25 |
26 | return html
27 | .replace('', `${markup}
`)
28 | .replace('React App', context.helmet.title.toString())
29 | .replace('', `${context.helmet.meta.toString()}`)
30 | .replace('', `${context.helmet.link.toString()}`)
31 | .replace('', `${sheets.getStyleTags()}`)
32 | .replace('', ``)
33 | }
34 |
--------------------------------------------------------------------------------
/server/router.ts:
--------------------------------------------------------------------------------
1 | import koa from 'koa'
2 | import http from 'koa-route'
3 | import serve from 'koa-static'
4 |
5 | import App from '../src/App'
6 | import { paths } from './config'
7 | import { render } from './lib/render'
8 |
9 | export const Router = new koa()
10 |
11 | const handler = (ctx: koa.Context) => {
12 | ctx.body = render(App, ctx.request.path)
13 | }
14 |
15 | Router.use(http.get('/', handler))
16 | Router.use(http.get('/index.html', handler))
17 |
18 | Router.use(serve(paths.assets))
19 |
20 | Router.use(http.get('*', handler))
21 |
--------------------------------------------------------------------------------
/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Helmet } from 'react-helmet-async'
3 | import { Route, Switch } from 'react-router'
4 | import styled, { createGlobalStyle } from 'styled-components'
5 |
6 | import { Details } from './pages/Details'
7 | import { NotFound } from './pages/Error'
8 | import { Home } from './pages/Home'
9 |
10 | import { Footer } from './components/Footer'
11 | import { Navigation } from './components/Navigation'
12 |
13 | const GlobalStyles = createGlobalStyle`
14 | body {
15 | margin: 0;
16 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
17 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
18 | sans-serif;
19 |
20 | -webkit-font-smoothing: antialiased;
21 | -moz-osx-font-smoothing: grayscale;
22 | }
23 | `
24 |
25 | const Wrapper = styled.div`
26 | text-align: center;
27 | `
28 |
29 | const App: React.FC = () => (
30 | <>
31 |
32 |
33 |
34 | {process.env.REACT_APP_NAME}
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 | >
50 | )
51 |
52 | export default App
53 |
--------------------------------------------------------------------------------
/src/components/Footer.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import styled from 'styled-components'
3 |
4 | const Link = styled.a`
5 | color: #9649cb;
6 | `
7 |
8 | const Wrapper = styled.div`
9 | font-weight: bold;
10 | color: #ccc;
11 | `
12 |
13 | export const Footer = () => (
14 |
15 | github.com/
16 | sbstjn/
17 | cra-serverless
18 |
19 | )
20 |
--------------------------------------------------------------------------------
/src/components/Navigation.tsx:
--------------------------------------------------------------------------------
1 | import React, { useCallback } from 'react'
2 | import { useLocation, NavLink } from 'react-router-dom'
3 | import styled from 'styled-components'
4 |
5 | const activeClassName = 'active'
6 |
7 | const StyledLink = styled(NavLink).attrs({
8 | activeClassName,
9 | })`
10 | color: tomato;
11 | font-weight: bold;
12 | border: 1px solid tomato;
13 | border-radius: 3px;
14 | text-decoration: none;
15 | padding: 2px 6px;
16 |
17 | :hover,
18 | &:active,
19 | &:visited {
20 | color: tomato;
21 | }
22 |
23 | &.${activeClassName} {
24 | color: red;
25 | }
26 | `
27 |
28 | const ListItem = styled.li`
29 | display: inline-block;
30 | padding: 5px 10px;
31 | `
32 |
33 | const List = styled.ul`
34 | list-style-type: none;
35 | margin: 0;
36 | padding: 0;
37 | `
38 |
39 | const Wrapper = styled.div`
40 | padding-top: 15px;
41 | `
42 |
43 | export const Navigation = () => {
44 | const location = useLocation()
45 |
46 | const isDetailsActive = useCallback(() => {
47 | return location.pathname.indexOf('details/') > -1
48 | }, [location.pathname])
49 |
50 | const random = Math.random()
51 | .toString(36)
52 | .substring(2, 15)
53 |
54 | return (
55 |
56 |
57 |
58 |
59 | Home
60 |
61 |
62 |
63 |
64 |
69 | Dynamic
70 |
71 |
72 |
73 |
74 | )
75 | }
76 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { render } from 'react-dom'
3 | import { HelmetProvider } from 'react-helmet-async'
4 | import { BrowserRouter } from 'react-router-dom'
5 |
6 | import App from './App'
7 | import * as serviceWorker from './serviceWorker'
8 |
9 | render(
10 |
11 |
12 |
13 |
14 | ,
15 | document.getElementById('root'),
16 | )
17 |
18 | // If you want your app to work offline and load faster, you can change
19 | // unregister() to register() below. Note this comes with some pitfalls.
20 | // Learn more about service workers: https://bit.ly/CRA-PWA
21 | serviceWorker.unregister()
22 |
--------------------------------------------------------------------------------
/src/pages/Details.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Helmet } from 'react-helmet-async'
3 | import { withRouter } from 'react-router'
4 |
5 | export const Details = withRouter(({ match: { params: { id } } }) => (
6 | <>
7 |
8 | Details: {id}
9 |
10 | Details: {id}
11 | >
12 | ))
13 |
--------------------------------------------------------------------------------
/src/pages/Error.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Helmet } from 'react-helmet-async'
3 |
4 | export const NotFound = () => (
5 | <>
6 |
7 | Not Found
8 |
9 | Not Found
10 | >
11 | )
12 |
--------------------------------------------------------------------------------
/src/pages/Home.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | export const Home = () => Home
4 |
--------------------------------------------------------------------------------
/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/src/serviceWorker.ts:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | type Config = {
24 | onSuccess?: (registration: ServiceWorkerRegistration) => void;
25 | onUpdate?: (registration: ServiceWorkerRegistration) => void;
26 | };
27 |
28 | export function register(config?: Config) {
29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
30 | // The URL constructor is available in all browsers that support SW.
31 | const publicUrl = new URL(
32 | process.env.PUBLIC_URL,
33 | window.location.href
34 | );
35 | if (publicUrl.origin !== window.location.origin) {
36 | // Our service worker won't work if PUBLIC_URL is on a different origin
37 | // from what our page is served on. This might happen if a CDN is used to
38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
39 | return;
40 | }
41 |
42 | window.addEventListener('load', () => {
43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
44 |
45 | if (isLocalhost) {
46 | // This is running on localhost. Let's check if a service worker still exists or not.
47 | checkValidServiceWorker(swUrl, config);
48 |
49 | // Add some additional logging to localhost, pointing developers to the
50 | // service worker/PWA documentation.
51 | navigator.serviceWorker.ready.then(() => {
52 | console.log(
53 | 'This web app is being served cache-first by a service ' +
54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
55 | );
56 | });
57 | } else {
58 | // Is not localhost. Just register service worker
59 | registerValidSW(swUrl, config);
60 | }
61 | });
62 | }
63 | }
64 |
65 | function registerValidSW(swUrl: string, config?: Config) {
66 | navigator.serviceWorker
67 | .register(swUrl)
68 | .then(registration => {
69 | registration.onupdatefound = () => {
70 | const installingWorker = registration.installing;
71 | if (installingWorker == null) {
72 | return;
73 | }
74 | installingWorker.onstatechange = () => {
75 | if (installingWorker.state === 'installed') {
76 | if (navigator.serviceWorker.controller) {
77 | // At this point, the updated precached content has been fetched,
78 | // but the previous service worker will still serve the older
79 | // content until all client tabs are closed.
80 | console.log(
81 | 'New content is available and will be used when all ' +
82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
83 | );
84 |
85 | // Execute callback
86 | if (config && config.onUpdate) {
87 | config.onUpdate(registration);
88 | }
89 | } else {
90 | // At this point, everything has been precached.
91 | // It's the perfect time to display a
92 | // "Content is cached for offline use." message.
93 | console.log('Content is cached for offline use.');
94 |
95 | // Execute callback
96 | if (config && config.onSuccess) {
97 | config.onSuccess(registration);
98 | }
99 | }
100 | }
101 | };
102 | };
103 | })
104 | .catch(error => {
105 | console.error('Error during service worker registration:', error);
106 | });
107 | }
108 |
109 | function checkValidServiceWorker(swUrl: string, config?: Config) {
110 | // Check if the service worker can be found. If it can't reload the page.
111 | fetch(swUrl, {
112 | headers: { 'Service-Worker': 'script' }
113 | })
114 | .then(response => {
115 | // Ensure service worker exists, and that we really are getting a JS file.
116 | const contentType = response.headers.get('content-type');
117 | if (
118 | response.status === 404 ||
119 | (contentType != null && contentType.indexOf('javascript') === -1)
120 | ) {
121 | // No service worker found. Probably a different app. Reload the page.
122 | navigator.serviceWorker.ready.then(registration => {
123 | registration.unregister().then(() => {
124 | window.location.reload();
125 | });
126 | });
127 | } else {
128 | // Service worker found. Proceed as normal.
129 | registerValidSW(swUrl, config);
130 | }
131 | })
132 | .catch(() => {
133 | console.log(
134 | 'No internet connection found. App is running in offline mode.'
135 | );
136 | });
137 | }
138 |
139 | export function unregister() {
140 | if ('serviceWorker' in navigator) {
141 | navigator.serviceWorker.ready.then(registration => {
142 | registration.unregister();
143 | });
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/src/setupTests.ts:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/tsconfig.cdk.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2018",
4 | "module": "commonjs",
5 | "lib": ["es2018", "dom"],
6 | "declaration": false,
7 | "strict": true,
8 | "noImplicitAny": true,
9 | "strictNullChecks": true,
10 | "noImplicitThis": true,
11 | "alwaysStrict": true,
12 | "noUnusedLocals": false,
13 | "noUnusedParameters": false,
14 | "noImplicitReturns": true,
15 | "noFallthroughCasesInSwitch": false,
16 | "inlineSourceMap": true,
17 | "inlineSources": true,
18 | "experimentalDecorators": true,
19 | "strictPropertyInitialization": false,
20 | "typeRoots": ["./node_modules/@types"]
21 | },
22 | "exclude": ["cdk.out", "aws"]
23 | }
24 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": ["dom", "dom.iterable", "esnext"],
5 | "allowJs": true,
6 | "skipLibCheck": true,
7 | "esModuleInterop": true,
8 | "allowSyntheticDefaultImports": true,
9 | "strict": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "module": "esnext",
12 | "moduleResolution": "node",
13 | "resolveJsonModule": true,
14 | "isolatedModules": true,
15 | "noEmit": true,
16 | "jsx": "react"
17 | },
18 | "exclude": ["cdk.out", "aws", "server"],
19 | "include": ["src"]
20 | }
21 |
--------------------------------------------------------------------------------
/tsconfig.server.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2018",
4 | "module": "commonjs",
5 | "types": ["node", "react"],
6 | "lib": ["es2018", "dom"],
7 | "outDir": ".server",
8 | "strict": true,
9 | "jsx": "react",
10 | "strictNullChecks": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "noImplicitThis": true,
14 | "alwaysStrict": true,
15 | "noImplicitReturns": true,
16 | "noFallthroughCasesInSwitch": false,
17 | "inlineSourceMap": true,
18 | "inlineSources": true,
19 | "experimentalDecorators": true,
20 | "strictPropertyInitialization": false,
21 |
22 | "typeRoots": ["./node_modules/@types"]
23 | },
24 | "include": ["server"],
25 | "exclude": ["cdk.out", "aws", "public"]
26 | }
27 |
--------------------------------------------------------------------------------