Skip to content

React Website

This generator creates a new React website with shadcn/ui configured by default, along with the AWS CDK or Terraform infrastructure to deploy your website to the cloud as a static website hosted in S3, served by CloudFront and protected by WAF.

The generated application uses Vite as the build tool and bundler. It uses TanStack Router for type-safe routing.

You can generate a new React Website in two ways:

Run this generator@aws/nx-plugin:ts#website

pnpm nx g @aws/nx-plugin:ts#website --framework=react
Build your command10

Required

Generator Options10 options
nameRequiredstring

The name of the application.

frameworkenumDefault: react

The frontend framework to use.

react
directorystringDefault: packages

The directory of the new application.

uxenumDefault: shadcn

The preferred UX provider.

nonecloudscapeshadcn
tailwindbooleanDefault: true

Enable TailwindCSS for utility-first styling.

tanstackRouterbooleanDefault: true

Enable Tanstack router for type-safe routing.

infraenumDefault: cloudfront-s3

The type of infrastructure to deploy your website with.

cloudfront-s3none
iacenumDefault: inherit

The preferred IaC provider. By default this is inherited from your initial selection.

inheritcdkterraform
subDirectorystring

The sub directory the project is placed in. By default this is the project name.

preferInstallDependenciesbooleanDefault: true

Whether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.

The generator will create the following project structure in the <directory>/<name> directory:

  • index.html HTML entry point
  • public Static assets
  • Directorysrc
    • main.tsx Application entry point with React setup
    • config.ts Application configuration (eg. logo)
    • Directorycomponents
      • AppLayout Components for the overall layout and navigation bar
      • app-sidebar.tsx Sidebar navigation (shadcn only)
      • alert.tsx Alert component wrapping your UX provider’s own
      • spinner.tsx Spinner component wrapping your UX provider’s own
    • Directoryhooks
      • useAppLayout.tsx Hook for adjusting the AppLayout from nested components (Cloudscape only)
    • Directoryroutes
      • __root.tsx Root route, wrapping every page in the AppLayout
      • index.tsx Example route (or page) for TanStack Router
    • routeTree.gen.ts Route tree, generated and maintained by TanStack Router
    • styles.css Global styles
  • vite.config.mts Vite and Vitest configuration
  • project.json Nx project defining the project’s targets
  • tsconfig.json Base TypeScript configuration for source and tests
  • tsconfig.app.json TypeScript configuration for source code
  • tsconfig.spec.json TypeScript configuration for tests
  • package.json Project manifest defining the project’s package name and dependencies
  • README.md Project README

Since this generator vends infrastructure as code based on your chosen iac, it will create a project in packages/common which includes the relevant CDK constructs or Terraform modules.

The common infrastructure as code project is structured as follows:

  • Directorypackages/common/constructs
    • Directorysrc
      • Directoryapp/ Constructs for infrastructure specific to a project/generator
        • …
      • Directorycore/ Generic constructs which are reused by constructs in app
        • …
      • index.ts Entry point exporting constructs from app
    • project.json Project build targets and configuration

The generator creates infrastructure as code for deploying your website based on your selected iac:

  • Directorypackages/common/constructs/src
    • Directoryapp
      • Directorystatic-websites
        • <name>.ts Infrastructure specific to your website
    • Directorycore
      • static-website.ts Generic StaticWebsite construct

The deployed website has the following architecture: your built assets in an S3 bucket, served by a CloudFront distribution with an AWS WAFv2 Web ACL in front of it.

Loading the diagram…

The React documentation is a good place to start to learn the basics of building with React.

ux = cloudscape

You can refer to the Cloudscape documentation for details about the available components and how to use them.

ux = shadcn

You can refer to the shadcn/ui documentation for details about the available components and how to use them.

Your website comes with TanStack Router configured by default. This makes it easy to add new routes:

  1. Run the Local Development Server
  2. Create a new <page-name>.tsx file in src/routes, with its position in the file tree representing the path
  3. Notice a Route and RouteComponent are automatically generated for you. You can start building your page here!

You can use the Link component or useNavigate hook to navigate between pages:

import { Link, useNavigate } from '@tanstack/react-router';
export const MyComponent = ({
createProduct,
}: {
createProduct: () => Promise<string>;
}) => {
const navigate = useNavigate();
const submit = async () => {
const id = await createProduct();
// Use `navigate` for redirecting after some asynchronous action
navigate({ to: '/products/$id', params: { id } });
};
return (
<>
<Link to="/products">Cancel</Link>
<button onClick={submit}>Submit</button>
</>
);
};

$id in the to path is a path parameter, supplied through params. Swap the plain <button> for your UX kit’s own button component as needed.

For more details, check out the TanStack Router documentation.

The React website generator creates CDK or Terraform infrastructure as code based on your selected iac. You can use this to deploy your website.

To deploy your website, we recommend using the ts#infra generator to create a CDK application.

You can use the CDK construct generated for you in packages/common/constructs to deploy your website.

packages/infra/src/stacks/application-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { MyWebsite } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
new MyWebsite(this, 'MyWebsite');
}
}

This sets up:

  1. An S3 bucket for hosting your static website files
  2. CloudFront distribution for global content delivery
  3. WAF Web ACL for security protection
  4. Origin Access Control for secure S3 access
  5. Automatic deployment of website files and runtime configuration

The CloudFront distribution applies a response headers policy that sets Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options: DENY, Referrer-Policy and a Content-Security-Policy on all responses.

A default Content-Security-Policy is enforced. It restricts scripts and framing to mitigate XSS and clickjacking, while permitting HTTPS and WSS connections so the website can call AWS service endpoints (such as API Gateway, Cognito and Bedrock AgentCore) whose URLs are only known at deploy time. To adjust the policy (for example to tighten connect-src to your specific origins), edit the content_security_policy value in your generated static-website.ts (CDK) or static-website.tf (Terraform).

runtime-config.json is served with Cache-Control: no-cache so that browsers always fetch the latest configuration after a redeploy, rather than using a stale cached copy.

The CloudFront distribution is protected by an AWS WAFv2 Web ACL by default. The Web ACL uses the AWS managed default ruleset (AWSManagedRulesCommonRuleSet and AWSManagedRulesKnownBadInputsRuleSet), providing protection against common web exploits including the OWASP Top 10.

To opt out, set enableWaf to false when you create your website:

packages/infra/src/stacks/application-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { MyWebsite, suppressRules } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const website = new MyWebsite(this, 'MyWebsite', {
enableWaf: false,
});
// Disabling WAF fails the checkov CKV_AWS_68 check ("CloudFront
// Distribution should have WAF enabled"). Suppress it explicitly.
suppressRules(
website.cloudFrontDistribution,
['CKV_AWS_68'],
'WAF is intentionally disabled for this distribution',
);
}
}

The website bucket, the CloudFront distribution log bucket, and the CloudWatch Logs group receiving their server access logs are encrypted with a customer-managed AWS KMS key by default. This key is created for you automatically, with key rotation enabled.

If you want to use a different encryption configuration, pass the encryption, encryptionKey and enableKeyRotation props when you create your website:

packages/infra/src/stacks/application-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { BucketEncryption } from 'aws-cdk-lib/aws-s3';
import { MyWebsite } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
new MyWebsite(this, 'MyWebsite', {
encryption: BucketEncryption.S3_MANAGED,
});
}
}

To use your own KMS key instead of one created automatically, pass encryptionKey:

new MyWebsite(this, 'MyWebsite', {
encryptionKey: myKey,
});

enableKeyRotation (default true) only applies to the automatically created key, i.e. when encryption is BucketEncryption.KMS (the default) and no encryptionKey is supplied:

new MyWebsite(this, 'MyWebsite', {
enableKeyRotation: false,
});

By default the distribution uses the default CloudFront domain name (*.cloudfront.net) and its default certificate, which does not support enforcing a minimum TLS version of 1.2. To serve your website from your own domain, supply an ACM certificate (which must reside in us-east-1 for use with CloudFront) and your domain names. A minimum TLS version of 1.2 is then enforced for viewers:

Pass the certificate and domainNames props when you create your website:

packages/infra/src/stacks/application-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
import { MyWebsite } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
new MyWebsite(this, 'MyWebsite', {
domainNames: ['www.example.com'],
certificate: Certificate.fromCertificateArn(this, 'Cert',
'arn:aws:acm:us-east-1:123456789012:certificate/...'),
});
}
}

You will also need to create DNS records (for example in Route 53) pointing your domain at the CloudFront distribution.

Instead of CloudFront, you can serve your website through the routes of an existing REST API, on the API’s own origin, with no CloudFront distribution and no cross-origin requests. This is supported with CDK only.

Generate the API first (with ts#smithy-api, or with ts#trpc-api or py#fast-api using REST infrastructure), then generate your website with hosting set to api-gateway:

Run this generator@aws/nx-plugin:ts#react-website

pnpm nx g @aws/nx-plugin:ts#react-website --name=my-website --hosting=api-gateway --apiProject=my-api
Build your command10

Required

The generated website construct then extends ApiGatewayStaticWebsite, which adds these routes to the API:

  • GET / and any path without a file extension return index.html, so routes of your app load directly.
  • GET /runtime-config.json returns the runtime configuration.
  • GET /assets/{proxy+} returns the files named by their content’s hash, cached for a year.
  • Any other path with a file extension returns that file from the bundle.

These routes need no authorization, while the API’s operations keep theirs. For an API with IAM authorization, the resource policy allows anyone every GET except the API’s own IAM operations, which still need an IAM grant. The API’s Web ACL covers the website too.

The website is built with a relative Vite base (./), and the router’s basepath comes from the page’s <base href>. The construct deploys a copy of index.html for each path the API is reached at, such as /prod/ on the execute-api URL or a custom domain’s base path, and serves each request the copy for its domain. So one build serves every URL of the API.

Pass your API to the website:

packages/infra/src/stacks/application-stack.ts
const identity = new UserIdentity(this, 'Identity');
const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
});
api.grantInvokeAccess(identity.identityPool.authenticatedRole);
new MyWebsite(this, 'MyWebsite');
new MyWebsite(this, 'MyWebsite', { api });

The User Pool’s web client permits every URL the website is served at as a callback, so sign-in returns to the URL it started from.

The website is also served from each custom domain that maps the API, whether you set the API’s domainName, call addDomainName, or map it with a DomainName of your own, before or after the website construct. On each domain it is served under the mapping’s base path: at https://app.example.com for an empty base path, or at https://example.com/app/ for app. The execute-api URL keeps serving it too.

  • url is always the execute-api URL, such as https://<api-id>.execute-api.<region>.amazonaws.com/prod/. It exists for every API and does not depend on which domains you add. The stack output WebsiteUrl names it.
  • urls lists every URL the website is served at: the execute-api URL first, then each custom domain sorted by domain name and base path. The stack output WebsiteUrls lists them, separated by spaces.

The construct never picks one domain over another. If you want a canonical domain, name it yourself, for example in an output of your own:

new CfnOutput(this, 'AppUrl', { value: 'https://app.example.com' });
  • The deployed website runs under a path such as /prod/, while the local dev server runs at the root. Link through the router or with relative URLs: a link starting with / works locally and breaks once deployed.
  • The runtime configuration names one URL for the API, which the website calls from whichever URL it was loaded at. The API allows every origin by default. If you restrict its CORS origins with restrictCorsTo, include the origin of each of the website’s urls.
  • Keep <base href="%BASE_URL%" /> in index.html. The construct writes the website’s path there in each copy it deploys, and the build loads everything relative to it.
  • The construct refuses to synthesise for an API with a GET operation at / or at a top-level path parameter such as /{id}, which would take the paths the website is served from.
  • Switching an existing website from CloudFront replaces its CloudFront website construct only if you have not changed it. Otherwise the generator stops: move your changes aside, delete the construct, and run the generator again.
  • If RuntimeConfig, CognitoAuth, UserIdentity or your API’s construct was generated by an older version of the plugin, the generator stops and names it. Run nx migrate @aws/nx-plugin, apply the migrations, and run the generator again.

Configuration from your infrastructure is provided to your website via Runtime Configuration. This allows your website to access details such as API URLs which are not known until your application is deployed.

The RuntimeConfig CDK construct can be used to add and retrieve configuration in your CDK infrastructure. The CDK constructs generated by @aws/nx-plugin generators (such as ts#api and py#api) will automatically add appropriate values to the RuntimeConfig.

Your website CDK construct will deploy the connection namespace of the runtime configuration as a runtime-config.json file to the root of your S3 bucket.

packages/infra/src/stacks/application-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { MyWebsite, MyApi } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// Website can be declared at any point, since runtime config is resolved lazily
new MyWebsite(this, 'MyWebsite');
// Automatically adds values to the RuntimeConfig
new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
});
}
}

In your website, you can use the useRuntimeConfig hook to retrieve values from the runtime configuration:

import { useRuntimeConfig } from '../hooks/useRuntimeConfig';
const MyComponent = () => {
const runtimeConfig = useRuntimeConfig();
// Access values in the runtime config here
const apiUrl = runtimeConfig.apis.MyApi;
};

When running the local development server, you will need a runtime-config.json file in your public directory in order for your local website to know the backend URLs, identity configuration, etc.

Your website project is configured with a load-runtime-config target which you can use to pull down the runtime-config.json file from a deployed application:

Terminal window
pnpm nx load-runtime-config <my-website>

The canonical command for local development is dev, which starts your website (and any local servers for APIs you’ve connected it to) with one command:

Terminal window
pnpm nx dev <my-website>

The serve target is also available for when you need to control how much of your application runs locally versus pointing at deployed AWS infrastructure. For a broader overview of local development across connected projects, including how dev behaves for projects with multiple components, see the Local Development guide.

The serve target starts a local development server for your website. This target requires you to have deployed any supporting infrastructure that the website interacts with, and have loaded local runtime configuration.

You can run this target with the following command:

Terminal window
pnpm nx serve <my-website>

This target is useful for working on website changes while pointing to “real” deployed APIs and other infrastructure.

The dev target starts a local development server for your website (with Vite MODE set to local-dev), as well as starting any local servers for APIs you have connected your website to via the Connection generator.

When your local website server is run via this target, runtime-config.json is automatically overridden to point to your locally running API urls.

You can run this target with the following command:

Terminal window
pnpm nx dev <my-website>

This target is useful when you are working across your website and API and wish to quickly iterate without deploying your infrastructure.

Mock Authentication

When run in this mode and no runtime-config.json is present, if you have configured Cognito Authentication (via the ts#website#auth generator), login will be skipped and requests to your local servers will not include authentication headers.

To enable login and authentication for dev, deploy your infrastructure and load runtime config.

You can build your website using the build target. This runs the bundle, compile, test and lint targets, type-checking, bundling, testing and linting your website.

Terminal window
pnpm nx build <my-website>

The bundle target uses Vite to create a production bundle in the root dist/packages/<my-website>/bundle directory. This is the deployable artifact consumed by your website infrastructure. You can run it on its own:

Terminal window
pnpm nx bundle <my-website>

Testing your website is much like writing tests in a standard TypeScript project, so please refer to the TypeScript project guide for more details.

For React specific testing, React Testing Library is already installed and available for you to use to write tests. For more details on its usage, please refer to the React Testing Library documentation.

You can run your tests using the test target:

Terminal window
pnpm nx test <my-website>

Use the connection generator to integrate this project with others in your workspace. The following connections involve this project:

tRPC
React to tRPCCall a tRPC API from a React website
FastAPI
React to FastAPICall a Python FastAPI from a React website
Smithy
React to Smithy APICall a Smithy API from a React website
Strands AgentsPython
React to Python AgentCall a Python Agent from a React website
Strands AgentsTypeScript
React to TypeScript AgentCall a TypeScript Agent from a React website
CopilotKit
React to AG-UI AgentCall an Agent exposing the AG-UI protocol from a React website via CopilotKit
Amazon Bedrock AgentCore Gateway
React Website to AgentCore GatewayConnect a React website to agents through an AgentCore Gateway