├── .gitignore ├── .prettierrc ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── app ├── .eslintrc.json ├── .gitignore ├── lib │ ├── useEnv.ts │ └── useUser.ts ├── next.config.ts ├── package-lock.json ├── package.json ├── pages │ ├── _app.tsx │ ├── admin.tsx │ ├── index.tsx │ └── signin.tsx ├── public │ ├── favicon.ico │ └── vercel.svg ├── styles │ ├── globals.css │ └── page.module.css └── tsconfig.json ├── cdk.json ├── cloudfrontfunction └── rewrite.js ├── lambda └── postConfirmation.ts ├── package-lock.json ├── package.json ├── provisioning.ts └── stack └── sample-stack.ts /.gitignore: -------------------------------------------------------------------------------- 1 | *.js 2 | *.d.ts 3 | node_modules 4 | !cloudfrontfunction/*.js 5 | 6 | # CDK asset staging directory 7 | .cdk.staging 8 | cdk.out 9 | -------------------------------------------------------------------------------- /.prettierrc : -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "none", 3 | "tabWidth": 2, 4 | "semi": false, 5 | "printWidth": 120, 6 | "singleQuote": true 7 | } 8 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Next.js Authentication UI using Amplify UI Components with Cognito 2 | 3 | ```bash 4 | npm ci && cd app && npm ci && cd .. 5 | npm run build 6 | 7 | npx cdk bootstrap 8 | npx cdk deploy AllInOneStack 9 | ``` 10 | 11 | | Page | | 12 | | --------- | --------------------------------------------------------- | 13 | | `/` | Public page that anyone can access | 14 | | `/admin` | Require auth, unauthenticated users redirect to `/signin` | 15 | | `/signin` | Authentication UI, return to `/admin` after auth | 16 | 17 | ## This is Server-side Rendering? 18 | 19 | No, this sample is a Single Page Application, generated with `next export`. The routing issue when using `next export` and S3 together is solved by [CloudFront Functions](cloudfrontfunction/rewrite.js) to rewrite the path. 20 | 21 | ## Deploy CDK stacks 22 | 23 | ### Deploy frontend and backend all at once 24 | 25 | This sample requires the frontend resource to refer Cognito resource built as a backend resource, but the AllInOneStack deploys frontend and backend resources all at once. 26 | 27 | #### Problem of deploying all at once 28 | 29 | There is no need to set backend resource information as environment variables on the frontend since they can be deployed all at once. On the other hand, since it is necessary to fetch and render information of backend resources from S3, that logic and loading component are required and readability may be reduced. 30 | 31 | #### How to deploy all at once 32 | 33 | Buit the frontend and deploy CDK stack without configuration Amplify such as Cognito User Pool ID. The CDK stack exports CDK deploy-time values such as Cognito User Pool ID to S3 using [aws_s3_deployment module](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_deployment-readme.html#data-with-deploy-time-values). During rendering, frontend fetches those resource information from S3 and configures them to Amplify. 34 | 35 | ### Deploy frontend and backend stacks separetly 36 | 37 | This sample also contains frontend and backend stack separately. 38 | 39 | #### How to deploy separetly 40 | 41 | When splitting stacks between frontend and backend, frontend stack needs to refer to resources such as Cognito in backend stack. Also, since the `aws_s3_deployment.Source.jsonData` method does not support cross-stack references by `Fn::ImportValue`, it is necessary to use reference by `Ref` or `Fn:GetAtt`. Therefore, if the stack is separated, it can be solved by using `RemoteOutputs` of [cdk-remote-stack](https://constructs.dev/packages/cdk-remote-stack/v/2.0.8?lang=typescript). 42 | 43 | #### Command to deploy separetly 44 | 45 | ```bash 46 | npx cdk deploy BackendStack 47 | npx cdk deploy FrontendStack 48 | ``` 49 | 50 | ## Run local dev server 51 | 52 | ```bash 53 | ## Create `./app/.env.development.local` and add Cognito UserPoolId and WebClientId. Refer to the following 54 | cat ./app/.env.development.local 55 | NEXT_PUBLIC_AUTH_USER_POOL_ID=ap-northeast-1_xxxxxxxxxxxx 56 | NEXT_PUBLIC_AUTH_WEB_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxx 57 | 58 | cd app 59 | npm run dev 60 | ``` 61 | 62 | ## Security 63 | 64 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 65 | 66 | ## License 67 | 68 | This library is licensed under the MIT-0 License. See the LICENSE file. 69 | -------------------------------------------------------------------------------- /app/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "next/core-web-vitals" 3 | } 4 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | .pnpm-debug.log* 27 | 28 | # local env files 29 | .env.local 30 | .env.development.local 31 | .env.test.local 32 | .env.production.local 33 | 34 | # vercel 35 | .vercel 36 | 37 | # typescript 38 | *.tsbuildinfo 39 | -------------------------------------------------------------------------------- /app/lib/useEnv.ts: -------------------------------------------------------------------------------- 1 | import useSWR from 'swr' 2 | 3 | const dev = process.env.NODE_ENV === 'development' 4 | 5 | interface Env { 6 | cognitoUserPoolId: string 7 | cognitoUserPoolWebClientId: string 8 | } 9 | 10 | const fetcher = async () => { 11 | const res = await fetch('/env.json') 12 | return res.json() 13 | } 14 | 15 | export default function useEnv() { 16 | const { data: env } = useSWR(dev ? null : '/env.json', fetcher, { 17 | revalidateOnFocus: false, 18 | revalidateOnReconnect: false, 19 | }) 20 | 21 | if (dev) { 22 | return { 23 | env: Object.freeze({ 24 | cognitoUserPoolId: process.env.NEXT_PUBLIC_AUTH_USER_POOL_ID, 25 | cognitoUserPoolWebClientId: process.env.NEXT_PUBLIC_AUTH_WEB_CLIENT_ID, 26 | }) as Env, 27 | } 28 | } 29 | 30 | return { env: Object.freeze(env) } 31 | } 32 | -------------------------------------------------------------------------------- /app/lib/useUser.ts: -------------------------------------------------------------------------------- 1 | import Router from 'next/router' 2 | import useSWR, { useSWRConfig } from 'swr' 3 | import { Auth } from 'aws-amplify' 4 | 5 | const fetcher = async () => { 6 | return Auth.currentAuthenticatedUser() 7 | } 8 | 9 | export default function useUser({ redirect = '' } = {}) { 10 | const { cache } = useSWRConfig() 11 | const { data: user, error } = useSWR('user', fetcher) 12 | 13 | const loading = !user && !error 14 | const loggedOut = error && error === 'The user is not authenticated' 15 | 16 | if (loggedOut && redirect) { 17 | Router.push({ pathname: redirect, query: { redirect: Router.asPath } }) 18 | } 19 | 20 | const signOut = async ({ redirect = '/' }) => { 21 | cache.delete('user') 22 | await Router.push(redirect) 23 | await Auth.signOut() 24 | } 25 | 26 | return { loading, loggedOut, user, signOut } 27 | } 28 | -------------------------------------------------------------------------------- /app/next.config.ts: -------------------------------------------------------------------------------- 1 | import type { NextConfig } from 'next' 2 | 3 | const nextConfig: NextConfig = { 4 | reactStrictMode: true 5 | } 6 | 7 | module.exports = nextConfig 8 | -------------------------------------------------------------------------------- /app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "dev": "npm run build:config && next dev", 5 | "build": "npm run build:config && next build && next export", 6 | "build:config": "esbuild next.config.ts --bundle --outfile=next.config.js --platform=node --target=es2020", 7 | "start": "next start", 8 | "lint": "next lint" 9 | }, 10 | "dependencies": { 11 | "@aws-amplify/ui-react": "^2.6.1", 12 | "aws-amplify": "^4.3.14", 13 | "next": "12.1.0", 14 | "react": "17.0.2", 15 | "react-dom": "17.0.2", 16 | "swr": "^1.2.2" 17 | }, 18 | "devDependencies": { 19 | "@types/node": "17.0.19", 20 | "@types/react": "17.0.39", 21 | "esbuild": "^0.14.27", 22 | "eslint": "8.9.0", 23 | "eslint-config-next": "12.1.0", 24 | "typescript": "4.5.5" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import '../styles/globals.css' 2 | import type { AppProps } from 'next/app' 3 | import Head from 'next/head' 4 | import { Amplify } from 'aws-amplify' 5 | import '@aws-amplify/ui-react/styles.css' 6 | import useEnv from '../lib/useEnv' 7 | 8 | function MyApp({ Component, pageProps }: AppProps) { 9 | const { env } = useEnv() 10 | if (!env) return <>Loading... 11 | 12 | Amplify.configure({ 13 | Auth: { 14 | userPoolId: env.cognitoUserPoolId, 15 | userPoolWebClientId: env.cognitoUserPoolWebClientId, 16 | }, 17 | }) 18 | 19 | return ( 20 | <> 21 | 22 | Create Next App 23 | 24 | 25 | 26 | 27 | 28 | 29 | ) 30 | } 31 | 32 | export default MyApp 33 | -------------------------------------------------------------------------------- /app/pages/admin.tsx: -------------------------------------------------------------------------------- 1 | import { NextPage } from 'next' 2 | import styles from '../styles/page.module.css' 3 | import useUser from '../lib/useUser' 4 | 5 | const Admin: NextPage = () => { 6 | const { user, loading, loggedOut, signOut } = useUser({ redirect: '/signin' }) 7 | 8 | if (loading) return <>Loading... 9 | if (loggedOut) return <>Redirect... 10 | 11 | console.log(user.signInUserSession?.idToken?.jwtToken) 12 | 13 | return ( 14 | <> 15 |
16 |

Welcome, {user.attributes?.email}!

17 | 18 |

19 | Sign out and redirect to home: 20 |

21 |
22 | 23 | ) 24 | } 25 | 26 | export default Admin 27 | -------------------------------------------------------------------------------- /app/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import type { NextPage } from 'next' 2 | import Router from 'next/router' 3 | import styles from '../styles/page.module.css' 4 | 5 | const Home: NextPage = () => { 6 | const moveToRequireAuthenticationPage = () => { 7 | Router.push('/admin') 8 | } 9 | 10 | return ( 11 |
12 |

13 | Welcome to Next.js! 14 |

15 | 16 |

17 | Move to the administrator screen: 18 |

19 |
20 | ) 21 | } 22 | 23 | export default Home 24 | -------------------------------------------------------------------------------- /app/pages/signin.tsx: -------------------------------------------------------------------------------- 1 | import { NextPage } from 'next' 2 | import Router from 'next/router' 3 | import { useSWRConfig } from 'swr' 4 | import styles from '../styles/page.module.css' 5 | import { Authenticator, useAuthenticator, CheckboxField, AmplifyProvider, Theme } from '@aws-amplify/ui-react' 6 | 7 | const themeBlue: Theme = { 8 | name: 'blue', 9 | tokens: { 10 | colors: { 11 | brand: { 12 | primary: { 13 | 10: { value: 'rgba(25,120,200,0.1)' }, 14 | 20: { value: 'rgba(25,120,200,0.2)' }, 15 | 40: { value: 'rgba(25,120,200,0.4)' }, 16 | 60: { value: 'rgba(25,120,200,0.6)' }, 17 | 80: { value: 'rgb(25,120,200)' }, 18 | 90: { value: 'rgb(25,120,200)' }, 19 | 100: { value: 'rgb(25,120,200)' }, 20 | }, 21 | }, 22 | }, 23 | }, 24 | } 25 | 26 | const AuthUI: NextPage = () => { 27 | const { route } = useAuthenticator((context) => [context.route]) 28 | const { cache } = useSWRConfig() 29 | 30 | if (route === 'authenticated') { 31 | cache.delete('user') 32 | const redirect = Router.query.redirect || '/' 33 | Router.push(redirect + '') 34 | return <>Redirect... 35 | } 36 | 37 | return ( 38 |
39 | 47 | 48 | 54 | I agree with the{' '} 55 | 61 | Terms & Conditions 62 | 63 | 64 | } 65 | /> 66 | 67 | ) 68 | }, 69 | }, 70 | }} 71 | services={{ 72 | async validateCustomSignUp(formData) { 73 | if (!formData.acknowledgement) { 74 | return { 75 | acknowledgement: 'You must agree to the Terms & Conditions', 76 | } 77 | } 78 | }, 79 | }} 80 | /> 81 |
82 | ) 83 | } 84 | 85 | const SignIn: NextPage = () => { 86 | return ( 87 | 88 | 89 | 90 | 91 | 92 | ) 93 | } 94 | 95 | export default SignIn 96 | -------------------------------------------------------------------------------- /app/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/nextjs-authentication-ui-using-amplify-ui-with-cognito/f4a1ca5a3ee1184a27f788502842e3efd33c5e93/app/public/favicon.ico -------------------------------------------------------------------------------- /app/public/vercel.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | -------------------------------------------------------------------------------- /app/styles/globals.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | padding: 0; 4 | margin: 0; 5 | font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, 6 | Helvetica Neue, sans-serif; 7 | } 8 | 9 | a { 10 | color: inherit; 11 | text-decoration: none; 12 | } 13 | 14 | * { 15 | box-sizing: border-box; 16 | } 17 | -------------------------------------------------------------------------------- /app/styles/page.module.css: -------------------------------------------------------------------------------- 1 | .container { 2 | padding: 0 2rem; 3 | } 4 | 5 | .main { 6 | min-height: 100vh; 7 | padding: 4rem 0; 8 | flex: 1; 9 | display: flex; 10 | flex-direction: column; 11 | justify-content: center; 12 | align-items: center; 13 | } 14 | 15 | .footer { 16 | display: flex; 17 | flex: 1; 18 | padding: 2rem 0; 19 | border-top: 1px solid #eaeaea; 20 | justify-content: center; 21 | align-items: center; 22 | } 23 | 24 | .footer a { 25 | display: flex; 26 | justify-content: center; 27 | align-items: center; 28 | flex-grow: 1; 29 | } 30 | 31 | .title a { 32 | color: #0070f3; 33 | text-decoration: none; 34 | } 35 | 36 | .title a:hover, 37 | .title a:focus, 38 | .title a:active { 39 | text-decoration: underline; 40 | } 41 | 42 | .title { 43 | margin: 0; 44 | line-height: 1.15; 45 | font-size: 4rem; 46 | } 47 | 48 | .title, 49 | .description { 50 | text-align: center; 51 | } 52 | 53 | .description { 54 | margin: 4rem 0; 55 | line-height: 1.5; 56 | font-size: 1.5rem; 57 | } 58 | 59 | .code { 60 | background: #fafafa; 61 | border-radius: 5px; 62 | padding: 0.75rem; 63 | font-size: 1.1rem; 64 | font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, 65 | Bitstream Vera Sans Mono, Courier New, monospace; 66 | } 67 | 68 | .grid { 69 | display: flex; 70 | align-items: center; 71 | justify-content: center; 72 | flex-wrap: wrap; 73 | max-width: 800px; 74 | } 75 | 76 | .card { 77 | margin: 1rem; 78 | padding: 1.5rem; 79 | text-align: left; 80 | color: inherit; 81 | text-decoration: none; 82 | border: 1px solid #eaeaea; 83 | border-radius: 10px; 84 | transition: color 0.15s ease, border-color 0.15s ease; 85 | max-width: 300px; 86 | } 87 | 88 | .card:hover, 89 | .card:focus, 90 | .card:active { 91 | color: #0070f3; 92 | border-color: #0070f3; 93 | } 94 | 95 | .card h2 { 96 | margin: 0 0 1rem 0; 97 | font-size: 1.5rem; 98 | } 99 | 100 | .card p { 101 | margin: 0; 102 | font-size: 1.25rem; 103 | line-height: 1.5; 104 | } 105 | 106 | .logo { 107 | height: 1em; 108 | margin-left: 0.5rem; 109 | } 110 | 111 | @media (max-width: 600px) { 112 | .grid { 113 | width: 100%; 114 | flex-direction: column; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /app/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve", 16 | "incremental": true 17 | }, 18 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], 19 | "exclude": ["node_modules"] 20 | } 21 | -------------------------------------------------------------------------------- /cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "npx ts-node --prefer-ts-exts provisioning.ts" 3 | } 4 | -------------------------------------------------------------------------------- /cloudfrontfunction/rewrite.js: -------------------------------------------------------------------------------- 1 | // @ts-ignore 2 | function handler(event) { 3 | var request = event.request 4 | var uri = request.uri 5 | 6 | if (uri === '/') { 7 | return request 8 | } 9 | 10 | if (uri.endsWith('/')) { 11 | return { 12 | statusCode: 302, 13 | statusDescription: 'Found', 14 | headers: { 15 | location: { 16 | value: uri.slice(0, -1) 17 | } 18 | } 19 | } 20 | } else if (!uri.includes('.')) { 21 | request.uri += '.html' 22 | } 23 | 24 | return request 25 | } 26 | -------------------------------------------------------------------------------- /lambda/postConfirmation.ts: -------------------------------------------------------------------------------- 1 | import { PostConfirmationTriggerHandler, PostConfirmationTriggerEvent } from 'aws-lambda' 2 | 3 | export const handler: PostConfirmationTriggerHandler = async (event: PostConfirmationTriggerEvent) => { 4 | if (event.triggerSource === 'PostConfirmation_ConfirmSignUp') { 5 | // Store User ID in a database, etc., if necessary. 6 | console.log(event.userName, event.request.userAttributes?.email) 7 | } 8 | 9 | return event 10 | } 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "@types/aws-lambda": "^8.10.92", 4 | "@types/node": "^17.0.19", 5 | "aws-cdk": "^2.13.0", 6 | "aws-cdk-lib": "^2.13.0", 7 | "aws-lambda": "^1.0.7", 8 | "cdk-remote-stack": "^2.0.8", 9 | "esbuild": "^0.14.23" 10 | }, 11 | "scripts": { 12 | "build": "cd app && npm run build" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /provisioning.ts: -------------------------------------------------------------------------------- 1 | import * as cdk from 'aws-cdk-lib' 2 | import { FrontendStack, BackendStack, AllInOneStack } from './stack/sample-stack' 3 | 4 | const app = new cdk.App() 5 | 6 | const backend = new BackendStack(app, 'BackendStack') 7 | const frontend = new FrontendStack(app, 'FrontendStack', { 8 | backendStack: backend 9 | }) 10 | frontend.addDependency(backend) 11 | 12 | new AllInOneStack(app, 'AllInOneStack') 13 | -------------------------------------------------------------------------------- /stack/sample-stack.ts: -------------------------------------------------------------------------------- 1 | import { Stack, StackProps, CfnOutput, Duration, RemovalPolicy } from 'aws-cdk-lib' 2 | import { Construct } from 'constructs' 3 | import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs' 4 | import * as cognito from 'aws-cdk-lib/aws-cognito' 5 | import * as s3 from 'aws-cdk-lib/aws-s3' 6 | import * as s3deploy from 'aws-cdk-lib/aws-s3-deployment' 7 | import * as cloudfront from 'aws-cdk-lib/aws-cloudfront' 8 | import * as path from 'path' 9 | import { RemoteOutputs } from 'cdk-remote-stack' 10 | 11 | export class AllInOneStack extends Stack { 12 | constructor(scope: Construct, id: string, props?: StackProps) { 13 | super(scope, id, props) 14 | 15 | const postConfirmationFn = new NodejsFunction(this, 'PostConfirmationFn', { 16 | entry: 'lambda/postConfirmation.ts' 17 | }) 18 | 19 | const userPool = new cognito.UserPool(this, 'UserPool', { 20 | selfSignUpEnabled: true, 21 | signInAliases: { 22 | email: true 23 | }, 24 | lambdaTriggers: { 25 | postConfirmation: postConfirmationFn 26 | } 27 | }) 28 | 29 | const userPoolClient = userPool.addClient('UserPoolClient', { 30 | authFlows: { 31 | userPassword: true, 32 | userSrp: true 33 | }, 34 | accessTokenValidity: Duration.days(1), 35 | idTokenValidity: Duration.days(1), 36 | refreshTokenValidity: Duration.days(30) 37 | }) 38 | 39 | new CfnOutput(this, 'CognitoUserPoolId', { 40 | value: userPool.userPoolId 41 | }) 42 | 43 | new CfnOutput(this, 'CognitoUserPoolWebClientId', { 44 | value: userPoolClient.userPoolClientId 45 | }) 46 | 47 | const websiteBucket = new s3.Bucket(this, 'WebsiteBucket', { 48 | websiteErrorDocument: '404.html', 49 | websiteIndexDocument: 'index.html', 50 | versioned: true, 51 | encryption: s3.BucketEncryption.S3_MANAGED, 52 | enforceSSL: true 53 | }) 54 | 55 | const websiteIdentity = new cloudfront.OriginAccessIdentity(this, 'WebsiteIdentity') 56 | websiteBucket.grantRead(websiteIdentity) 57 | 58 | const rewriteFn = new cloudfront.Function(this, 'RewriteFunction', { 59 | code: cloudfront.FunctionCode.fromFile({ 60 | filePath: 'cloudfrontfunction/rewrite.js' 61 | }) 62 | }) 63 | 64 | const websiteDistribution = new cloudfront.CloudFrontWebDistribution(this, 'WebsiteDistribution', { 65 | errorConfigurations: [ 66 | { 67 | errorCachingMinTtl: 300, 68 | errorCode: 404, 69 | responseCode: 200, 70 | responsePagePath: '/404.html' 71 | } 72 | ], 73 | originConfigs: [ 74 | { 75 | s3OriginSource: { 76 | s3BucketSource: websiteBucket, 77 | originAccessIdentity: websiteIdentity 78 | }, 79 | behaviors: [ 80 | { 81 | isDefaultBehavior: true, 82 | functionAssociations: [ 83 | { 84 | eventType: cloudfront.FunctionEventType.VIEWER_REQUEST, 85 | function: rewriteFn 86 | } 87 | ] 88 | } 89 | ] 90 | } 91 | ], 92 | priceClass: cloudfront.PriceClass.PRICE_CLASS_ALL 93 | }) 94 | 95 | const frontendEnvVars = { 96 | cognitoUserPoolId: userPool.userPoolId, 97 | cognitoUserPoolWebClientId: userPoolClient.userPoolClientId 98 | } 99 | 100 | new s3deploy.BucketDeployment(this, 'WebsiteDeploy', { 101 | sources: [ 102 | s3deploy.Source.asset(path.join(__dirname, '..', 'app', 'out')), 103 | s3deploy.Source.jsonData('env.json', frontendEnvVars) 104 | ], 105 | destinationBucket: websiteBucket, 106 | distribution: websiteDistribution, 107 | distributionPaths: ['/*'], 108 | memoryLimit: 1024 109 | }) 110 | 111 | new CfnOutput(this, 'FrontendEndpoint', { 112 | description: 'Frontend Endpoint', 113 | value: websiteDistribution.distributionDomainName 114 | }) 115 | } 116 | } 117 | 118 | export class BackendStack extends Stack { 119 | constructor(scope: Construct, id: string, props?: StackProps) { 120 | super(scope, id, props) 121 | 122 | const postConfirmationFn = new NodejsFunction(this, 'PostConfirmationFn', { 123 | entry: 'lambda/postConfirmation.ts' 124 | }) 125 | 126 | const userPool = new cognito.UserPool(this, 'UserPool', { 127 | selfSignUpEnabled: true, 128 | signInAliases: { 129 | email: true 130 | }, 131 | lambdaTriggers: { 132 | postConfirmation: postConfirmationFn 133 | } 134 | }) 135 | 136 | const userPoolClient = userPool.addClient('UserPoolClient', { 137 | authFlows: { 138 | userPassword: true, 139 | userSrp: true 140 | }, 141 | accessTokenValidity: Duration.days(1), 142 | idTokenValidity: Duration.days(1), 143 | refreshTokenValidity: Duration.days(30) 144 | }) 145 | 146 | new CfnOutput(this, 'CognitoUserPoolId', { 147 | value: userPool.userPoolId 148 | }) 149 | 150 | new CfnOutput(this, 'CognitoUserPoolWebClientId', { 151 | value: userPoolClient.userPoolClientId 152 | }) 153 | } 154 | 155 | getOutputsForFrontend(scope: Stack) { 156 | const outputs = new RemoteOutputs(scope, 'BackendStackOutputs', { stack: this }) 157 | const cognitoUserPoolId = outputs.get('CognitoUserPoolId') 158 | const cognitoUserPoolWebClientId = outputs.get('CognitoUserPoolWebClientId') 159 | 160 | return { 161 | cognitoUserPoolId, 162 | cognitoUserPoolWebClientId 163 | } 164 | } 165 | } 166 | 167 | interface FrontendStackProps extends StackProps { 168 | backendStack: BackendStack 169 | } 170 | 171 | export class FrontendStack extends Stack { 172 | constructor(scope: Construct, id: string, props: FrontendStackProps) { 173 | super(scope, id, props) 174 | 175 | const websiteBucket = new s3.Bucket(this, 'WebsiteBucket', { 176 | websiteErrorDocument: '404.html', 177 | websiteIndexDocument: 'index.html', 178 | versioned: true, 179 | encryption: s3.BucketEncryption.S3_MANAGED, 180 | enforceSSL: true 181 | }) 182 | 183 | const websiteIdentity = new cloudfront.OriginAccessIdentity(this, 'WebsiteIdentity') 184 | websiteBucket.grantRead(websiteIdentity) 185 | 186 | const rewriteFn = new cloudfront.Function(this, 'RewriteFunction', { 187 | code: cloudfront.FunctionCode.fromFile({ 188 | filePath: 'cloudfrontfunction/rewrite.js' 189 | }) 190 | }) 191 | 192 | const websiteDistribution = new cloudfront.CloudFrontWebDistribution(this, 'WebsiteDistribution', { 193 | errorConfigurations: [ 194 | { 195 | errorCachingMinTtl: 300, 196 | errorCode: 404, 197 | responseCode: 200, 198 | responsePagePath: '/404.html' 199 | } 200 | ], 201 | originConfigs: [ 202 | { 203 | s3OriginSource: { 204 | s3BucketSource: websiteBucket, 205 | originAccessIdentity: websiteIdentity 206 | }, 207 | behaviors: [ 208 | { 209 | isDefaultBehavior: true, 210 | functionAssociations: [ 211 | { 212 | eventType: cloudfront.FunctionEventType.VIEWER_REQUEST, 213 | function: rewriteFn 214 | } 215 | ] 216 | } 217 | ] 218 | } 219 | ], 220 | priceClass: cloudfront.PriceClass.PRICE_CLASS_ALL 221 | }) 222 | 223 | const frontendEnvVars = props.backendStack.getOutputsForFrontend(this) 224 | 225 | new s3deploy.BucketDeployment(this, 'WebsiteDeploy', { 226 | sources: [ 227 | s3deploy.Source.asset(path.join(__dirname, '..', 'app', 'out')), 228 | s3deploy.Source.jsonData('env.json', frontendEnvVars) 229 | ], 230 | destinationBucket: websiteBucket, 231 | distribution: websiteDistribution, 232 | distributionPaths: ['/*'], 233 | memoryLimit: 1024 234 | }) 235 | 236 | new CfnOutput(this, 'FrontendEndpoint', { 237 | description: 'Frontend Endpoint', 238 | value: websiteDistribution.distributionDomainName 239 | }) 240 | } 241 | } 242 | --------------------------------------------------------------------------------