tRPC
tRPC is a framework for building APIs in TypeScript with end-to-end type safety. Using tRPC, updates to API operation inputs and outputs are immediately reflected in client code and are visible in your IDE without the need to rebuild your project.
The tRPC API generator creates a new tRPC API with AWS CDK or Terraform infrastructure setup. The generated backend is exposed via an AWS API Gateway API, and includes schema validation using Zod. It sets up AWS Lambda Powertools for observability, including structured logging and CloudWatch metrics.
AWS X-Ray tracing is set up too.
Your procedures run on AWS Lambda, so there is no server to manage and you pay only for the requests you serve.
Your procedures run as a long-lived HTTP server in a container on Amazon ECS, behind an API Gateway HTTP API. See Running on Amazon ECS for what that changes, including why X-Ray tracing produces no traces there.
Generate a tRPC API
Section titled “Generate a tRPC API”You can generate a new tRPC API in two ways:
Run this generator@aws/nx-plugin:ts#api
pnpm nx g @aws/nx-plugin:ts#api --framework=trpc yarn nx g @aws/nx-plugin:ts#api --framework=trpc npx nx g @aws/nx-plugin:ts#api --framework=trpc bunx nx g @aws/nx-plugin:ts#api --framework=trpc- Install the Nx Console VSCode Plugin if you haven't already
- Open the Nx Console in VSCode
- Click
Generate (UI)in the "Common Nx Commands" section - Search for
@aws/nx-plugin - ts#api - Fill in the required parameters
- framework: trpc
- Click
Generate
Build your command10
Required
Options
Section titled “Options”nameRequiredstringThe name of the API (required). Used to generate class names and file paths.
frameworkenumDefault:trpcThe API framework to use.
trpcsmithyintegrationPatternenumHow API Gateway integrations are generated for the API. Choose between isolated and shared. Defaults to isolated. The http-ecs infrastructure always uses shared, since one container service answers every operation, so isolated is ignored there with a warning.
isolatedsharedauthenumDefault:iamThe method used to authenticate with your API. Choose between iam (default), cognito or custom.
iamcognitocustomdirectorystringDefault:packagesThe directory to store the application in.
iacenumDefault:inheritThe preferred IaC provider. By default this is inherited from your initial selection.
inheritcdkterraforminfraenumDefault:rest-lambdaThe type of infrastructure to use to deploy this API. http-ecs (experimental) runs the API as a container service on Amazon ECS behind an API Gateway HTTP API, and requires the trpc framework and the CDK IaC provider. It always uses integrationPattern shared, since one container service answers every operation.
rest-lambdahttp-lambdahttp-ecsnonesubDirectorystringThe sub directory the project is placed in. By default this is the project name.
architectureenumThe CPU architecture your container image is built for and its ECS task runs on. Applies to the http-ecs infrastructure. ARM64 runs on AWS Graviton, which costs less per task on AWS Fargate. By default this is the architecture of the machine you run the generator on, and re-running keeps the architecture already generated.
ARM64X86_64preferInstallDependenciesbooleanDefault:trueWhether 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.
Generator Output
Section titled “Generator Output”The generator will create the following project structure in the <directory>/<api-name> directory:
Directorysrc
- index.ts Package entrypoint re-exporting the router, context, client and schema
- init.ts Backend tRPC initialisation
- handler.ts Lambda handler entrypoint
- router.ts tRPC router definition
Directoryschema Schema definitions using Zod
- index.ts Barrel re-exporting every schema
- echo.ts Example definitions for the input and output of the “echo” procedure
- z-async-iterable.ts Zod helper for subscriptions (REST API only)
Directoryprocedures Procedures (or operations) exposed by your API
- echo.ts Example procedure
Directorymiddleware
- index.ts Barrel re-exporting the middleware, and the procedure context type
- error.ts Middleware for error handling
- logger.ts middleware for configuring AWS Powertools for Lambda logging
- tracer.ts middleware for configuring AWS Powertools for Lambda tracing
- metrics.ts middleware for configuring AWS Powertools for Lambda metrics
- local-server.ts tRPC standalone adapter entrypoint for local development server
Directoryclient
- index.ts Type-safe client for machine-to-machine API calls
- rolldown.config.ts Bundle configuration for the Lambda deployment package
- tsconfig.json TypeScript configuration
- tsconfig.lib.json TypeScript configuration for the library sources
- tsconfig.spec.json TypeScript configuration for the tests
- vitest.config.mts Vitest configuration
- package.json Project manifest defining the project’s package name and dependencies
- project.json Project configuration and build targets
- README.md Project readme
- .gitignore Ignores the project’s build output
With infra set to http-ecs the API runs as an HTTP server rather than a Lambda handler, so src/handler.ts and src/local-server.ts are not generated. In their place you get a container folder named after your API:
Directorysrc
Directory<api-name>-container/
- server.ts The
node:httpserver:GET /health, and the tRPC standalone adapter for every procedure - index.ts Entry point that reads
PORTandHOSTand starts the server. The bundle, the image and theservetarget all start from this file - Dockerfile Container image definition
- .dockerignore Files left out of the image build context
- server.ts The
Your router, procedures, schema, middleware and client are the same for every infra value.
Infrastructure
Section titled “Infrastructure”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
Directorypackages/common/terraform
Directorysrc
Directoryapp/ Terraform modules for infrastructure specific to a project/generator
- …
Directorycore/ Generic modules which are reused by modules in
app- …
- project.json Project build targets and configuration
For deploying your API, the following files are generated:
Directorypackages/common/constructs/src
Directoryapp
Directoryapis
- <project-name>.ts CDK construct for deploying your API
Directorycore
Directoryapi
- http-api.ts CDK construct for deploying an HTTP API (if you selected to deploy an HTTP API)
- rest-api.ts CDK construct for deploying a REST API (if you selected to deploy a REST API)
- utils.ts Utilities for the API constructs
Directorypackages/common/terraform/src
Directoryapp
Directoryapis
Directory<project-name>
- <project-name>.tf Module for deploying your API
Directorycore
Directoryapi
Directoryhttp-api
- http-api.tf Module for deploying an HTTP API (if you selected to deploy an HTTP API)
Directoryrest-api
- rest-api.tf Module for deploying a REST API (if you selected to deploy a REST API)
Architecture
Section titled “Architecture”The deployed application has the following architecture: an API Gateway API in front of a Lambda function running your handler.
REST APIs include an AWS WAFv2 Web ACL in front of the API Gateway stage with the AWS managed default ruleset enabled.
HTTP APIs do not support WAF directly — if you need WAF protection, choose REST API instead or front the HTTP API with a CloudFront distribution.
Implementing your tRPC API
Section titled “Implementing your tRPC API”At a high-level, tRPC APIs consist of a router which delegates requests to specific procedures. Each procedure has an input and output, defined as a Zod schema.
Schema
Section titled “Schema”The src/schema directory contains the types that are shared between your client and server code. In this package, these types are defined using Zod, a TypeScript-first schema declaration and validation library.
An example schema might look as follows:
import { z } from 'zod';
// Schema definitionexport const UserSchema = z.object({ name: z.string(), height: z.number(), dateOfBirth: z.string().datetime(),});
// Corresponding TypeScript typeexport type User = z.TypeOf<typeof UserSchema>;Given the above schema, the User type is equivalent to the following TypeScript:
interface User { name: string; height: number; dateOfBirth: string;}Schemas are shared by both server and client code, providing a single place to update when making changes to the structures used in your API.
Schemas are automatically validated by your tRPC API at runtime, which saves hand-crafting custom validation logic in your backend.
Zod provides powerful utilities to combine or derive schemas such as .merge, .pick, .omit and more. You can find more information on the Zod documentation website.
Router and Procedures
Section titled “Router and Procedures”Your tRPC router is defined in src/router.ts, which registers all procedures. Each procedure defines the expected input, output, and implementation.
The Lambda handler entry point is in src/handler.ts, which forwards requests to your router.
The entry point is src/<api-name>-container/server.ts, the HTTP server the container runs, which forwards requests to your router.
The sample router generated for you has a single operation, called echo:
import { echo } from './procedures/echo.js';
export const appRouter = router({ echo,});The example echo procedure is generated for you in src/procedures/echo.ts:
export const echo = publicProcedure .input(EchoInputSchema) .output(EchoOutputSchema) .query((opts) => ({ message: opts.input.message }));To break down the above:
publicProceduredefines a public method on the API, including the middleware set up insrc/middleware. This middleware includes AWS Lambda Powertools integration for logging, tracing and metrics.inputaccepts a Zod schema which defines the expected input for the operation. Requests sent for this operation are automatically validated against this schema.outputaccepts a Zod schema which defines the expected output for the operation. You will see type errors in your implementation if you don’t return an output which conforms to the schema.queryaccepts a function which defines the implementation for your API. This implementation receivesopts, which contains theinputpassed to your operation, as well as other context set up by middleware, available inopts.ctx. The function passed toquerymust return an output which conforms to theoutputschema.
The use of query to define the implementation indicates that the operation is not mutative. Use this to define methods to retrieve data. To implement a mutative operation, use the mutation method instead.
If you add a new procedure, make sure you register it by adding it to the router in src/router.ts.
Subscriptions (Streaming)
Section titled “Subscriptions (Streaming)”tRPC subscriptions allow you to stream data from the server to the client using Server-Sent Events (SSE). When you select rest-lambda as your compute type, the generator automatically configures the infrastructure required for streaming, as well as a streaming Lambda handler and the ZodAsyncIterable schema helper.
To define a subscription procedure, use the .subscription method with an async generator function. Use the ZodAsyncIterable helper from src/schema/z-async-iterable.ts to define the output schema:
import { publicProcedure } from '../init.js';import { z } from 'zod';import { ZodAsyncIterable } from '../schema/z-async-iterable.js';
const InputSchema = z.object({ query: z.string() });const ChunkSchema = z.object({ text: z.string() });
export const myStream = publicProcedure .input(InputSchema) .output( ZodAsyncIterable({ yield: ChunkSchema, }), ) .subscription(async function* (opts) { // Yield data to the client as it becomes available for (const chunk of await getResults(opts.input.query)) { yield { text: chunk }; } });Register the subscription in your router just like any other procedure:
export const appRouter = router({ echo, myStream,});The generated infrastructure uses a streaming Lambda handler with ResponseTransferMode.STREAM in API Gateway for all REST API operations, which enables subscriptions to work alongside regular queries and mutations.
Customising your tRPC API
Section titled “Customising your tRPC API”Errors
Section titled “Errors”In your implementation, you can return error responses to clients by throwing a TRPCError. These accept a code which indicates the type of error, for example:
throw new TRPCError({ code: 'NOT_FOUND', message: 'The requested resource could not be found',});Organising Your Operations
Section titled “Organising Your Operations”As your API grows, you may wish to group related operations together.
You can group operations together using nested routers, for example:
import { getUser } from './procedures/users/get.js';import { listUsers } from './procedures/users/list.js';
const appRouter = router({ users: router({ get: getUser, list: listUsers, }), ...})Clients then receive this grouping of operations, for example invoking the listUsers operation in this case might look as follows:
client.users.list.query();Logging
Section titled “Logging”The AWS Lambda Powertools logger is configured in src/middleware/logger.ts, and can be accessed in an API implementation via opts.ctx.logger. You can use this to log to CloudWatch Logs, and/or control additional values to include in every structured log message. For example:
export const echo = publicProcedure .input(...) .output(...) .query(async (opts) => { opts.ctx.logger.info('Operation called with input', opts.input);
return ...; });For more information about the logger, please refer to the AWS Lambda Powertools Logger documentation.
Recording Metrics
Section titled “Recording Metrics”AWS Lambda Powertools metrics are configured in src/middleware/metrics.ts, and can be accessed in an API implementation via opts.ctx.metrics. You can use this to record metrics in CloudWatch without the need to import and use the AWS SDK, for example:
export const echo = publicProcedure .input(...) .output(...) .query(async (opts) => { opts.ctx.metrics.addMetric('Invocations', 'Count', 1);
return ...; });For more information, please refer to the AWS Lambda Powertools Metrics documentation.
Fine-tuning X-Ray Tracing
Section titled “Fine-tuning X-Ray Tracing”The AWS Lambda Powertools tracer is configured in src/middleware/tracer.ts, and can be accessed in an API implementation via opts.ctx.tracer. You can use this to add traces with AWS X-Ray to provide detailed insights into the performance and flow of API requests. For example:
export const echo = publicProcedure .input(...) .output(...) .query(async (opts) => { const subSegment = opts.ctx.tracer.getSegment()!.addNewSubsegment('MyAlgorithm'); // ... my algorithm logic to capture subSegment.close();
return ...; });For more information, please refer to the AWS Lambda Powertools Tracer documentation.
Implementing Custom Middleware
Section titled “Implementing Custom Middleware”You can add additional values to the context provided to procedures by implementing middleware.
As an example, let’s implement some middlware to extract some details about the calling user from our API in src/middleware/identity.ts.
This example walks through identity middleware for IAM authentication. We look up the caller in Cognito using the sub extracted from the API Gateway event.
The lookup uses the Cognito Identity Provider client, which is not a dependency of a generated tRPC API. Install it into your API project first:
pnpm add @aws-sdk/client-cognito-identity-provider@3.1179.0 --filter my-apiyarn workspace @my-scope/my-api add @aws-sdk/client-cognito-identity-provider@3.1179.0npm install --legacy-peer-deps @aws-sdk/client-cognito-identity-provider@3.1179.0 -w packages/my-apibun add @aws-sdk/client-cognito-identity-provider@3.1179.0 --cwd packages/my-apiFirst, we define what we’ll add to the context:
export interface IIdentityContext { identity?: { sub: string; username: string; };}Note that we define an additional optional property to the context. tRPC manages ensuring that this is defined in procedures which have correctly configured this middleware.
Next, we’ll implement the middlware itself. This has the following structure:
export const createIdentityPlugin = () => { const t = initTRPC.context<...>().create(); return t.procedure.use(async (opts) => { // Add logic here to run before the procedure
const response = await opts.next(...);
// Add logic here to run after the procedure
return response; });};In our case, we want to extract details about the calling Cognito user. We’ll do that by extracting the user’s subject ID (or “sub”) from the API Gateway event, and retrieving user details from Cognito. The implementation varies depending on whether the event was provided to our function by a REST API or an HTTP API:
import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';import { initTRPC, TRPCError } from '@trpc/server';import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';import type { APIGatewayProxyEvent } from 'aws-lambda';
export interface IIdentityContext { identity?: { sub: string; username: string; };}
export const createIdentityPlugin = () => { const t = initTRPC .context< IIdentityContext & CreateAWSLambdaContextOptions<APIGatewayProxyEvent> >() .create();
const cognito = new CognitoIdentityProvider();
return t.procedure.use(async (opts) => { const cognitoAuthenticationProvider = opts.ctx.event.requestContext?.identity?.cognitoAuthenticationProvider;
let sub: string | undefined = undefined; if (cognitoAuthenticationProvider) { const providerParts = cognitoAuthenticationProvider.split(':'); sub = providerParts[providerParts.length - 1]; }
if (!sub) { throw new TRPCError({ code: 'FORBIDDEN', message: `Unable to determine calling user`, }); }
const { Users } = await cognito.listUsers({ // Assumes user pool id is configured in lambda environment UserPoolId: process.env.USER_POOL_ID!, Limit: 1, Filter: `sub="${sub}"`, });
if (!Users || Users.length !== 1) { throw new TRPCError({ code: 'FORBIDDEN', message: `No user found with subjectId ${sub}`, }); }
// Provide the identity to other procedures in the context return await opts.next({ ctx: { ...opts.ctx, identity: { sub, username: Users[0].Username!, }, }, }); });};import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';import { initTRPC, TRPCError } from '@trpc/server';import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';import type { APIGatewayProxyEventV2WithIAMAuthorizer } from 'aws-lambda';
export interface IIdentityContext { identity?: { sub: string; username: string; };}
export const createIdentityPlugin = () => { const t = initTRPC .context< IIdentityContext & CreateAWSLambdaContextOptions<APIGatewayProxyEventV2WithIAMAuthorizer> >() .create();
const cognito = new CognitoIdentityProvider();
return t.procedure.use(async (opts) => { const cognitoIdentity = opts.ctx.event.requestContext?.authorizer?.iam ?.cognitoIdentity as unknown as | { amr: string[]; } | undefined;
const sub = (cognitoIdentity?.amr ?? []) .flatMap((s) => (s.includes(':CognitoSignIn:') ? [s] : [])) .map((s) => { const parts = s.split(':'); return parts[parts.length - 1]; })?.[0];
if (!sub) { throw new TRPCError({ code: 'FORBIDDEN', message: `Unable to determine calling user`, }); }
const { Users } = await cognito.listUsers({ // Assumes user pool id is configured in lambda environment UserPoolId: process.env.USER_POOL_ID!, Limit: 1, Filter: `sub="${sub}"`, });
if (!Users || Users.length !== 1) { throw new TRPCError({ code: 'FORBIDDEN', message: `No user found with subjectId ${sub}`, }); }
// Provide the identity to other procedures in the context return await opts.next({ ctx: { ...opts.ctx, identity: { sub, username: Users[0].Username!, }, }, }); });};When you deploy with auth: 'cognito', the API Gateway Cognito authorizer verifies the JWT that the caller supplies in the Authorization header and places the verified claims on the Lambda event. Our middleware just reads those claims — no extra AWS SDK calls, no manual JWT verification.
First, we define what we’ll add to the context:
export interface IIdentityContext { identity?: { sub: string; username: string; };}Note that we define an additional optional property on the context. tRPC manages ensuring that this is defined in procedures which have correctly configured this middleware.
Next, the middleware itself. The event type and the location of the claims differ between a REST API and an HTTP API, so the implementation depends on your selected infra:
A REST API’s Cognito User Pools authorizer places the claims at event.requestContext.authorizer.claims:
import { initTRPC, TRPCError } from '@trpc/server';import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';import type { APIGatewayProxyEvent } from 'aws-lambda';
export interface IIdentityContext { identity?: { sub: string; username: string; };}
export const createIdentityPlugin = () => { const t = initTRPC .context< IIdentityContext & CreateAWSLambdaContextOptions<APIGatewayProxyEvent> >() .create();
return t.procedure.use(async (opts) => { const claims = opts.ctx.event.requestContext?.authorizer?.claims as | Record<string, string> | undefined;
const sub = claims?.sub; const username = claims?.username ?? claims?.['cognito:username'];
if (!sub || !username) { throw new TRPCError({ code: 'FORBIDDEN', message: 'Unable to determine calling user', }); }
return await opts.next({ ctx: { ...opts.ctx, identity: { sub, username, }, }, }); });};An HTTP API’s JWT authorizer delivers a payload-v2 event whose claims sit one level deeper, at event.requestContext.authorizer.jwt.claims. The context must be typed on APIGatewayProxyEventV2WithJWTAuthorizer to match the one the generated publicProcedure uses — otherwise .concat() fails with tRPC’s Context mismatch error:
import { initTRPC, TRPCError } from '@trpc/server';import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';import type { APIGatewayProxyEventV2WithJWTAuthorizer } from 'aws-lambda';
export interface IIdentityContext { identity?: { sub: string; username: string; };}
export const createIdentityPlugin = () => { const t = initTRPC .context< IIdentityContext & CreateAWSLambdaContextOptions<APIGatewayProxyEventV2WithJWTAuthorizer> >() .create();
return t.procedure.use(async (opts) => { const claims = opts.ctx.event.requestContext?.authorizer?.jwt?.claims as | Record<string, string> | undefined;
const sub = claims?.sub; const username = claims?.username ?? claims?.['cognito:username'];
if (!sub || !username) { throw new TRPCError({ code: 'FORBIDDEN', message: 'Unable to determine calling user', }); }
return await opts.next({ ctx: { ...opts.ctx, identity: { sub, username, }, }, }); });};You can then mix the plugin into any procedure that needs the caller’s identity:
import { publicProcedure } from '../init.js';import { createIdentityPlugin } from '../middleware/identity.js';import { z } from 'zod';
export const me = publicProcedure .concat(createIdentityPlugin()) .output(z.object({ sub: z.string(), username: z.string() })) .query(({ ctx }) => ({ sub: ctx.identity!.sub, username: ctx.identity!.username, }));Deploying your tRPC API
Section titled “Deploying your tRPC API”The tRPC API generator creates CDK or Terraform infrastructure as code based on your selected iac. You can use this to deploy your tRPC API.
The CDK construct for deploying your API lives in the common/constructs folder. You can consume this in a CDK application, for example:
import { MyApi } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Add the api to your stack const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(), }); }}import { MyApi, UserIdentity } from '@my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Add the api to your stack const identity = new UserIdentity(this, 'Identity');
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(), identity, }); }}The UserIdentity construct can be generated using the ts#website#auth generator.
defaultIntegrations takes the VPC your service runs in, and builds everything inside it: the ECS service, the internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through. The construct never creates a VPC, so you create or import one in your stack.
import { MyApi } from '@my-scope/common-constructs';import { Stack } from 'aws-cdk-lib';import { Vpc } from 'aws-cdk-lib/aws-ec2';import { Construct } from 'constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { super(scope, id);
const vpc = new Vpc(this, 'Vpc', { natGateways: 1 });
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this, { vpc }).build(), }); }}To use an existing VPC, look it up with Vpc.fromLookup(this, 'Vpc', { vpcId: '<vpc-id>' }) and pass it as vpc.
Pass service to change the container service itself — its cpu, memoryLimitMiB, desiredCount, environment, or grantTaskRole to give the task role a permission:
MyApi.defaultIntegrations(this, { vpc, service: { cpu: 512, memoryLimitMiB: 1024, grantTaskRole: (taskRole) => myTable.grantReadWriteData(taskRole), },}).build();With auth set to cognito, also pass identity to the construct as the Cognito example above does.
This sets up your API infrastructure, including an AWS API Gateway REST or HTTP API, AWS Lambda functions for business logic, and authentication based on your chosen auth method.
This sets up an AWS API Gateway HTTP API with authentication based on your chosen auth method, an Amazon ECS service running your container, an internal load balancer in front of it, and the VPC link API Gateway reaches that load balancer through.
The Terraform modules for deploying your API are in the common/terraform folder. You can use this in a Terraform configuration.
The API module stages its Lambda deployment zip in a shared S3 asset bucket — see the Terraform infrastructure guide for details. Instantiate the core/asset-bucket module once per deployment and pass its bucket_name output into every API / Lambda module via the asset_bucket_name input:
module "asset_bucket" { source = "../../common/terraform/src/core/asset-bucket"}
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
# Environment variables for the Lambda function env = { ENVIRONMENT = var.environment LOG_LEVEL = "INFO" }
# Additional IAM policies if needed additional_iam_policy_statements = [ # Add any additional permissions your API needs ]
tags = local.common_tags}module "asset_bucket" { source = "../../common/terraform/src/core/asset-bucket"}
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
user_pool_id = local.user_pool_id user_pool_client_ids = [local.client_id]
# Environment variables for the Lambda function env = { ENVIRONMENT = var.environment LOG_LEVEL = "INFO" }
# Additional IAM policies if needed additional_iam_policy_statements = [ # Add any additional permissions your API needs ]
tags = local.common_tags}You can set up the Cognito User Pool and Client using the appropriate Terraform resources or modules.
This sets up:
- An AWS Lambda function that serves all tRPC procedures
- API Gateway HTTP/REST API as the function trigger
- IAM roles and permissions
- CloudWatch log group
- X-Ray tracing configuration
- CORS configuration
The Terraform module provides several outputs you can use:
# Access the API endpoint (the custom domain URL, if one is configured)output "api_url" { value = module.my_api.api_url}
# Access Lambda function detailsoutput "lambda_function_name" { value = module.my_api.lambda_function_name}
# Access IAM role for granting additional permissionsoutput "lambda_execution_role_arn" { value = module.my_api.lambda_execution_role_arn}You can customize CORS settings by passing variables to the module:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
# Custom CORS configuration cors_allow_origins = ["https://myapp.com", "https://staging.myapp.com"] cors_allow_methods = ["GET", "POST", "PUT", "DELETE"] cors_allow_headers = [ "authorization", "content-type", "x-custom-header" ]
tags = local.common_tags}For REST APIs, the generated construct associates an AWS WAFv2 Web ACL with the API Gateway stage 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. WAF request logs are written to a CloudWatch Logs group.
You can edit the generated rest-api construct to add, remove, or adjust rules (for example, to add rate-based rules or additional managed rule groups).
To opt out (for example, to attach your own Web ACL), set enableWaf to false:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(), enableWaf: false,});To opt out (for example, to attach your own Web ACL), set enable_waf to false:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name enable_waf = false}Access logging
Section titled “Access logging”For REST APIs, the generated infrastructure enables access logging by default, writing one structured JSON line per request to a dedicated CloudWatch Logs group. The log group is encrypted with a customer-managed KMS key and retained for one year.
API Gateway writes access logs using an account-level CloudWatch Logs role. This role is configured on the AWS::ApiGateway::Account setting, which is a singleton per region per account — there is only one role for every REST API in the region. To manage this safely across multiple independently-deployed stacks, the generated infrastructure:
- Creates a shared CloudWatch Logs role and configures it on the account only when no working role is already set, so deployments never overwrite a role another stack owns.
- Leaves the account setting untouched on teardown, so destroying one stack never disables logging for other REST APIs in the region.
The account role is managed by the ApiGatewayAccount construct, a stack-scoped singleton resolved via ApiGatewayAccount.ensure(scope). Each REST API’s stage depends on it, and the role is configured by a Lambda-backed custom resource.
The access log format is set by the RestApi construct your API extends. To customise it, pass deployOptions through to super in the generated packages/common/constructs/src/app/apis/my-api.ts, keeping the tracingEnabled the construct already sets:
super(scope, id, { apiName: 'MyApi', // ... deployOptions: { tracingEnabled: true, accessLogFormat: AccessLogFormat.clf(), }, ...props,});AccessLogFormat is imported from aws-cdk-lib/aws-apigateway. Anything you leave unset keeps the construct’s default — a JSON format with the standard fields.
The account role is managed by the core/api/api-gateway-account module, which is instantiated by the generated API module. It configures the account idempotently and is never reset on terraform destroy.
You can customise the access log format by editing the access_log_settings block on the aws_api_gateway_stage resource in the generated API module.
Custom domain
Section titled “Custom domain”By default your API is served from the endpoint API Gateway generates for it (https://<id>.execute-api.<region>.amazonaws.com/...). To serve it from your own domain instead, supply your domain name and an ACM certificate for it. The custom domain uses a regional endpoint by default, so the certificate must be in the same region as your API. A minimum TLS version of 1.2 is used by default.
When a custom domain is configured, the API’s URL in Runtime Configuration is the custom domain URL, so your website and other clients call your domain rather than the generated endpoint.
Pass the domain through to super in the generated packages/common/constructs/src/app/apis/my-api.ts:
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
super(scope, id, { apiName: 'MyApi', // ... domainName: { domainName: 'api.example.com', certificate: Certificate.fromCertificateArn( scope, 'MyApiCertificate', 'arn:aws:acm:<region>:123456789012:certificate/...', ), }, ...props,});The API is served at the root of the domain, without the stage path prefix (/prod/). To serve it under a path instead, set basePath on domainName; the URL in runtime configuration includes it. basePath is only available in CDK; the Terraform module always serves the API at the root of the domain.
import { DomainName } from 'aws-cdk-lib/aws-apigatewayv2';import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
super(scope, id, { apiName: 'MyApi', // ... defaultDomainMapping: { domainName: new DomainName(scope, 'MyApiDomainName', { domainName: 'api.example.com', certificate: Certificate.fromCertificateArn( scope, 'MyApiCertificate', 'arn:aws:acm:<region>:123456789012:certificate/...', ), }), }, ...props,});When a custom domain is configured, the stack outputs MyApiDomainNameAlias, the domain name to point your DNS record at, and MyApiDomainNameAliasHostedZoneId.
Set the custom_domain_name and acm_certificate_arn variables on the API module:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api" # ...
custom_domain_name = "api.example.com" acm_certificate_arn = "arn:aws:acm:<region>:123456789012:certificate/..."}The module outputs custom_domain_target_domain_name, the regional domain name to point your DNS record at, and custom_domain_hosted_zone_id. Its api_url output is the URL clients should call: the custom domain URL when one is configured, otherwise the stage invoke URL.
Finally, create a DNS record for your domain. With any DNS provider, create a CNAME record pointing your domain at the domain name output above. If your domain is hosted in Route 53, you can create an alias record instead, using the hosted zone ID output, which also works at the zone apex (e.g. example.com).
Integrations
Section titled “Integrations”The REST/HTTP API CDK constructs are configured to provide a type-safe interface for defining integrations for each of your operations.
Default Integrations
Section titled “Default Integrations”You can use the static defaultIntegrations to make use of the default pattern, which defines an individual AWS Lambda function for each operation:
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(),});The generated module already defines the default integrations for the pattern the API was generated with, so no additional configuration is needed:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
tags = local.common_tags}With the default isolated pattern, this creates one Lambda function per operation.
Accessing Integrations
Section titled “Accessing Integrations”You can access the underlying AWS Lambda functions via the API construct’s integrations property, in a type-safe manner. For example, if your API defines an operation named sayHello and you need to add some permissions to this function, you can do so as follows:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(),});
// sayHello is typed to the operations defined in your APIapi.integrations.sayHello.handler.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: [...], resources: [...],}));If your API uses the shared pattern, the shared router Lambda is exposed as api.integrations.$router:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(),});
api.integrations.$router.handler.addEnvironment('LOG_LEVEL', 'DEBUG');Note that $router is no longer available if you override every operation via withOverrides, since no operation is left using the default router integration.
With the isolated pattern, the module’s outputs are maps keyed by operation name, so you can reach a single operation’s resources. For example, to grant one operation’s Lambda function extra permissions:
# Grant additional permissions to just the sayHello operation's functionresource "aws_iam_role_policy" "say_hello_permissions" { name = "say-hello-additional-permissions" role = module.my_api.lambda_execution_role_names["sayHello"]
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "s3:GetObject", "s3:PutObject" ] Resource = "arn:aws:s3:::my-bucket/*" } ] })}To grant the same permissions to every operation, iterate the operations output:
resource "aws_iam_role_policy" "additional_permissions" { for_each = toset(module.my_api.operations)
name = "additional-api-permissions" role = module.my_api.lambda_execution_role_names[each.key]
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = ["s3:GetObject"] Resource = "arn:aws:s3:::my-bucket/*" } ] })}The module also exposes lambda_function_names, lambda_function_arns, lambda_invoke_arns, integration_ids and lambda_log_group_names as maps keyed by operation name. With the shared pattern the equivalent singular outputs (lambda_execution_role_name, lambda_function_name, …) are exposed instead, since there is only one function.
Permissions every operation needs are better passed to the module, which applies them to each function’s role:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
additional_iam_policy_statements = [ { Effect = "Allow" Action = ["s3:GetObject"] Resource = ["arn:aws:s3:::my-bucket/*"] } ]}Customising Default Options
Section titled “Customising Default Options”If you would like to customise the options used when creating the Lambda function for each default integration, you can use the withDefaultOptions method. For example, if you would like all of your Lambda functions to reside in a Vpc:
const vpc = new Vpc(this, 'Vpc', ...);
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withDefaultOptions({ vpc, }) .build(),});VPC configuration is already supported by the generated module — set enable_vpc along with vpc_id and subnet_ids, and the module deploys every Lambda function into your VPC behind a shared security group it creates for you:
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name
# VPC configuration enable_vpc = true vpc_id = aws_vpc.main.id subnet_ids = [aws_subnet.private_a.id, aws_subnet.private_b.id]
tags = local.common_tags}For options the module does not expose, edit the aws_lambda_function resource in the generated Terraform module directly. With the isolated pattern that single resource is declared for_each = local.operations, so an edit there applies to every operation.
Customising Options Per-Operation
Section titled “Customising Options Per-Operation”To customise the options used to create the default integration for specific operations (without affecting the others), you can use the withOperationOptions method. For example, if you would like to increase the Lambda function timeout for just one operation:
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOperationOptions({ sayHello: { timeout: Duration.seconds(60), }, }) .build(),});
// The selected operations remain default integrations, so they're still typed accordingly:api.integrations.sayHello.handler.addToRolePolicy(new PolicyStatement({ ... }));The options you specify are merged with the default integration options (and any options set via withDefaultOptions). Note that you cannot specify options for operations which you have replaced via withOverrides, since these no longer use the default integration.
You will encounter a type error if the same operation is targeted by both withOperationOptions and withOverrides, regardless of the order in which you call them.
With the isolated pattern the Lambda function resource is already per-operation, so options can be varied by operation name. For example, to give one operation a longer timeout, edit the aws_lambda_function resource in the generated module:
resource "aws_lambda_function" "api_lambda" { for_each = local.operations
# Default to 30 seconds, but allow longer for specific operations timeout = lookup({ sayHello = 60 }, each.key, 30)
# ... rest of configuration}Overriding Integrations
Section titled “Overriding Integrations”You can also override integrations for specific operations using the withOverrides method. Each override must specify an integration property which is typed to the appropriate CDK integration construct for the HTTP or REST API. The withOverrides method is also type-safe. For example, if you would like to override a getDocumentation API to point to documentation hosted by some external website you could achieve this as follows:
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOverrides({ getDocumentation: { integration: new HttpIntegration('https://example.com/documentation'), }, }) .build(),});You will also notice that the overridden integration no longer has a handler property when accessing it via api.integrations.getDocumentation.
You can add additional properties to an integration which will also be typed accordingly, allowing for other types of integration to be abstracted but remain type-safe, for example if you have created an S3 integration for a REST API and later wish to reference the bucket for a particular operation, you can do so as follows:
const storageBucket = new Bucket(this, 'Bucket', { ... });
const apiGatewayRole = new Role(this, 'ApiGatewayS3Role', { assumedBy: new ServicePrincipal('apigateway.amazonaws.com'),});
storageBucket.grantRead(apiGatewayRole);
const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOverrides({ getFile: { bucket: storageBucket, integration: new AwsIntegration({ service: 's3', integrationHttpMethod: 'GET', path: `${storageBucket.bucketName}/{fileName}`, options: { credentialsRole: apiGatewayRole, requestParameters: { 'integration.request.path.fileName': 'method.request.querystring.fileName', }, integrationResponses: [{ statusCode: '200' }], }, }), options: { requestParameters: { 'method.request.querystring.fileName': true, }, methodResponses: [{ statusCode: '200', }], } }, }) .build(),});
// Later, perhaps in another file, you can access the bucket property we defined// in a type-safe mannerapi.integrations.getFile.bucket.grantRead(...);To point a specific operation at a different integration type, exclude it from the default for_each and declare its integration separately. For example, to serve getDocumentation from an external website:
# Exclude the overridden operation from the default per-operation resourceslocals { overridden_operations = ["getDocumentation"] default_operations = { for op, details in local.operations : op => details if !contains(local.overridden_operations, op) }}
# Then use local.default_operations in place of local.operations for the# aws_lambda_function, aws_iam_role, aws_apigatewayv2_integration and# aws_lambda_permission resources, and add the override:resource "aws_apigatewayv2_integration" "get_documentation" { api_id = module.http_api.api_id integration_type = "HTTP_PROXY" integration_uri = "https://example.com/documentation" integration_method = "GET"}
resource "aws_apigatewayv2_route" "get_documentation" { api_id = module.http_api.api_id route_key = local.route_key["getDocumentation"] target = "integrations/${aws_apigatewayv2_integration.get_documentation.id}"}Overriding Authorizers
Section titled “Overriding Authorizers”You can also supply options in your integration to override particular method options such as authorizers, for example if you wished to use Cognito authentication for your getDocumentation operation:
new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this) .withOverrides({ getDocumentation: { integration: new HttpIntegration('https://example.com/documentation'), options: { authorizer: new CognitoUserPoolsAuthorizer(...) // for REST, or HttpUserPoolAuthorizer for an HTTP API } }, }) .build(),});Authorization is set on the route (HTTP API) or method (REST API) for each operation, so it can be varied by operation name. For example, to leave one operation unauthenticated on an HTTP API:
resource "aws_apigatewayv2_route" "operation_routes" { for_each = local.operations
# ... rest of configuration
authorization_type = each.key == "getDocumentation" ? "NONE" : "AWS_IAM"}For an IAM-authenticated REST API, also add a resource policy statement allowing unauthenticated access to that operation’s path.
Explicit Integrations
Section titled “Explicit Integrations”If you prefer, you can choose not to use the default integrations and instead directly supply one for each operation. This is useful if, for example, each operation needs to use a different type of integration or you would like to receive a type error when adding new operations:
new MyApi(this, 'MyApi', { integrations: { sayHello: { integration: new LambdaIntegration(...), }, getDocumentation: { integration: new HttpIntegration(...), }, },});Replace the for_each used by the isolated pattern with explicit instantiations of the Lambda functions, integrations and permissions for each operation.
Integration Pattern
Section titled “Integration Pattern”Generated APIs support two integration patterns:
isolatedcreates one Lambda function per operation. This is the default and recommended option for APIs.sharedcreates a single default router Lambda and reuses it for every operation unless you override specific integrations.
isolated gives you finer-grained permissions and configuration per operation, as well as better separation for logs and traces. shared reduces the likelihood of encountering cold-starts for low-usage APIs.
The integration pattern can be changed at any time in CDK by updating your API construct. For example, setting pattern to 'shared' creates a single function instead of one per integration:
export class MyApi<...> extends ... {
public static defaultIntegrations = (scope: Construct) => { ... return IntegrationBuilder.rest({ pattern: 'shared', ... }); };}Unlike CDK, the integration pattern is baked into the generated module. To change the integration pattern:
- Delete the previously generated API module in
packages/common/terraform/src/app/apis - Re-run the generator that created your API with the other integration pattern (eg
--integrationPattern=shared)
With the isolated pattern, the module reads the operations from a generated file:
locals { operations_file = "${path.module}/../../../generated/my-api/operations.json" operations = fileexists(local.operations_file) ? jsondecode(file(local.operations_file)) : {}}This file is generated from your API, so you do not need to edit this by hand. Adding an operation to your API application code adds the route and lambda function on the next deploy. It is .gitignored by default; remove the entry if you prefer to check it in.
Terraform REST API Path Depth Limit
Section titled “Terraform REST API Path Depth Limit”Granting Access (IAM Only)
Section titled “Granting Access (IAM Only)”You can grant access to your API as follows:
api.grantInvokeAccess(myIdentityPool.authenticatedRole);# Create an IAM policy to allow invoking the APIresource "aws_iam_policy" "api_invoke_policy" { name = "MyApiInvokePolicy" description = "Policy to allow invoking the tRPC API"
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = "execute-api:Invoke" Resource = "${module.my_api.api_execution_arn}/*/*" } ] })}
# Attach the policy to an IAM role (e.g., for authenticated users)resource "aws_iam_role_policy_attachment" "api_invoke_access" { role = aws_iam_role.authenticated_user_role.name policy_arn = aws_iam_policy.api_invoke_policy.arn}
# Or attach to an existing role by nameresource "aws_iam_role_policy_attachment" "api_invoke_access_existing" { role = "MyExistingRole" policy_arn = aws_iam_policy.api_invoke_policy.arn}The key outputs from the API module that you can use for IAM policies are:
module.my_api.api_execution_arn- For granting execute-api:Invoke permissionsmodule.my_api.api_arn- The API Gateway ARNmodule.my_api.lambda_function_arn- The Lambda function ARN
Bundle Target
Section titled “Bundle Target”The generator automatically configures a bundle target which uses Rolldown to create a deployment package:
pnpm nx bundle <project-name>yarn nx bundle <project-name>npx nx bundle <project-name>bunx nx bundle <project-name>Rolldown configuration can be found in rolldown.config.ts, with an entry per bundle to generate. Rolldown manages creating multiple bundles in parallel if defined.
Running on Amazon ECS
Section titled “Running on Amazon ECS”With infra set to http-ecs, your procedures run as a long-lived HTTP server in a container rather than in a Lambda function. A request takes this path:
- A caller signs a request to the API Gateway HTTP API, which is the only public entry point. Every route carries the authorizer for the
authyou chose, so an unauthenticated request is rejected at the edge. - API Gateway forwards the request through a VPC link, which is its private path into your VPC.
- The VPC link reaches an internal load balancer. The load balancer has no public address, and its only inbound rule allows the VPC link’s security group on the listener port.
- The load balancer forwards the request to a task. The tasks’ only inbound rule allows the load balancer’s security group on the container port, so nothing else in the VPC can open a connection to them.
The tasks run in private subnets and never get a public IP address. Nothing in this path allows an address range inbound.
By default the service, the load balancer and the VPC link go in the VPC’s PRIVATE_WITH_EGRESS subnets, which reach AWS through a NAT gateway. Passing vpcSubnets: { subnetType: SubnetType.PRIVATE_ISOLATED } to defaultIntegrations drops the NAT gateway and its hourly charge, but isolated subnets have no route out, so the VPC then needs four VPC endpoints for the tasks to start at all: interface endpoints for ecr.api and ecr.dkr to pull the image, an S3 gateway endpoint because the image layers are S3 objects, and an interface endpoint for logs so the awslogs driver can write. Without them a task cannot pull its image and ECS rolls the deployment back on the circuit breaker without saying why.
The VPC link, the load balancer, its listener, the target group and the bucket the load balancer writes its access logs to are created by one construct, core/api/ecs-http-endpoint.ts in common/constructs, which every API hosted on ECS shares. Your API’s own construct names its container service and routes every operation to that endpoint.
What Runs in the Container
Section titled “What Runs in the Container”src/<api-name>-container/server.ts is a node:http server with two jobs. GET /health answers {"status":"ok"}, which is what the load balancer’s target group and the container health check call. Every other request goes to the tRPC standalone adapter, which resolves it against your router.
There is no API Gateway event in the container, so the procedure context carries no event, context or info field: for http-ecs the vended IMiddlewareContext names only what the middleware puts there. The authorizer still decides whether a request reaches the container at all, but its claims do not arrive with the request, so the identity middleware examples above do not apply. To read the caller’s identity in a procedure, map the authorizer’s context onto a request header in your API construct and read that header.
Observability
Section titled “Observability”Logs and metrics work as they do on Lambda: the container writes to its own CloudWatch log group, and the metrics plugin publishes each request’s metrics in the embedded metric format for CloudWatch Logs to extract.
The metrics plugin builds a metrics object for each request and hands it to your procedures as opts.ctx.metrics, so a metric one request adds is never published with another’s. That matters more here than on Lambda, where one invocation owns the metrics from start to finish; this server handles requests at the same time. Add your own metrics through opts.ctx.metrics rather than a Metrics object of your own, which would share one store across every request in the process.
AWS X-Ray tracing does not. Powertools turns its tracer off outside Lambda, and there is no X-Ray daemon in the task to receive segments, so opts.ctx.tracer calls run without error and produce no traces. Add a daemon as a sidecar in your container service if you need them.
The API Gateway HTTP API’s access log records every request that reaches the API. The load balancer writes its own access logs to a bucket the EcsHttpEndpoint construct creates, which is where you can see which task served a request and what it answered.
Image Build and Scanning
Section titled “Image Build and Scanning”The container generator vends the image targets, named after your API:
<api-name>-container-dockerbuilds a linux/arm64 image, runningbundlefirst so the image holds the bundled server.<api-name>-container-trivyscans that image for vulnerabilities.
See TypeScript Container Service for how the image is built, and Docker Bundling for how it is published at deploy time.
Deploying and Tearing Down
Section titled “Deploying and Tearing Down”deploy-sandbox deploys in CloudFormation express mode, which returns once each resource’s configuration is applied rather than waiting for the ECS service to reach a steady state. So the target can finish while the first task is still starting, and until a task has passed two health checks fifteen seconds apart the load balancer has no target to send a request to and answers 503. Wait a minute or two and call again. A 503 that never clears is a real failure rather than a slow start: the service’s deployment circuit breaker rolls it back when no task becomes healthy.
The API’s URL is a stack output, but not under the name you would guess. The CfnOutput is created inside your API construct and nothing overrides its logical ID, so CDK builds the output key from the construct’s path plus an eight-character hash: an API added as new MyApi(this, 'MyApi', …) outputs MyApiMyApiUrl and that hash, not MyApiUrl. cdk deploy prints the value, and a script should match on the suffix rather than the whole key:
aws cloudformation describe-stacks --stack-name <stack-name> \ --query "Stacks[0].Outputs[?contains(OutputKey, 'Url')].OutputValue" --output textdestroy-sandbox leaves the HTTP API’s access log group and the customer-managed KMS key that encrypts it behind. Neither sets a removal policy, so CDK’s default of Retain applies and CloudFormation skips them rather than deleting them. List them before you tear the stack down, since a deleted stack no longer reports its resources:
aws cloudformation describe-stack-resources --stack-name <stack-name> \ --query "StackResources[?contains(LogicalResourceId, 'AccessLogs') && (ResourceType=='AWS::Logs::LogGroup' || ResourceType=='AWS::KMS::Key')].[ResourceType,PhysicalResourceId]" \ --output textThen remove them with aws logs delete-log-group --log-group-name <log-group-name> and aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7, seven days being the shortest window KMS accepts.
API Gateway accepts one VPC link deletion every 30 seconds per account, and that quota cannot be raised. Every http-ecs API in a stack that uses the same VPC shares one VPC link, so a stack deletes a single link however many of these APIs it holds. Nothing is shared across a stack boundary, and a nested stack counts as its own stack, so stacks torn down at the same time in one account can still clash. If a stack ends in DELETE_FAILED on a VPC link, wait 30 seconds and delete the stack again.
Upgrading from a release that gave each API its own link needs one check, if the stack already deployed three or more of these APIs on one VPC. The next deploy keeps the first API’s link and deletes the others in a single cleanup phase, so the second deletion goes out seconds after the first and API Gateway throttles it. The stack events then show DELETE_FAILED on a VPC link and on its security group, which cannot be deleted while the link still uses it, and the update takes about 20 minutes longer while CloudFormation retries both in the same cleanup. It deletes them on a later attempt and the update ends UPDATE_COMPLETE. Once it has completed, check the stack events, or the VPC links list in the API Gateway console, for a link still in DELETE_FAILED. Wait 30 seconds and delete any link in that state, then its security group. A link left behind counts against the ten-per-Region quota until it is gone; its security group does not.
Limits
Section titled “Limits”- Integration timeout. API Gateway HTTP APIs cap an integration at about 30 seconds. A procedure that takes longer than that fails at the gateway however long the container keeps working.
- No streaming. tRPC subscriptions need the
rest-lambdainfrastructure. An HTTP API cannot stream a response. - Payload size. Requests and responses follow API Gateway’s 10 MB limit.
- VPC links per Region. API Gateway allows ten VPC links per account per Region, raisable through Service Quotas. APIs sharing a stack and a VPC share one link, so what counts against the quota is stacks and VPCs rather than APIs.
- One service for every operation.
integrationPatternisshared: there is one container service, and every route is routed to it. The option always resolves tosharedfor this infrastructure, andisolatedis ignored with a warning.
The load balancer is the new fixed cost compared with Lambda, where you pay per request and nothing when idle. Rough monthly figures in us-east-1, before data transfer:
| Item | Approximately |
|---|---|
| Internal load balancer | $16 plus load balancer capacity units |
| Fargate task, 0.25 vCPU / 0.5 GB arm64 | $7 per task |
| NAT gateway, if your VPC has one | $33 |
| VPC link | no hourly charge |
| S3 storage for the load balancer’s access logs | cents per GB a month |
So a one-task service costs roughly $23 a month before any traffic, and more if the VPC you pass in has a NAT gateway. The access logs grow with traffic: add a lifecycle rule to endpoint.accessLogsBucket to expire them. Check the Elastic Load Balancing and AWS Fargate pricing pages for current prices in your Region.
Local tRPC Server
Section titled “Local tRPC Server”You can use the serve target to run a local server for your API, for example:
pnpm nx serve my-apiyarn nx serve my-apinpx nx serve my-apibunx nx serve my-apiThe entry point for the local server is src/local-server.ts.
The entry point for the local server is src/<api-name>-container/index.ts, the same file the container runs. It listens on the address in HOST, which defaults to 127.0.0.1, so the local server accepts connections only from your own machine. The image sets HOST=0.0.0.0 so the server listens on the task’s own network interface, where the task’s security group decides who may connect.
Check that the server is up with its health route, which returns status 200 and {"status":"ok"}:
curl http://localhost:2022/healthThis will automatically reload when you make changes to your API.
Invoking your tRPC API
Section titled “Invoking your tRPC API”You can create a tRPC client to invoke your API in a type-safe manner. If you are calling your tRPC API from another backend, you can use the client in src/client/index.ts, for example:
import { createMyApiClient } from '@my-scope/my-api';
const client = createMyApiClient({ url: 'https://my-api-url.example.com/' });
await client.echo.query({ message: 'Hello world!' });If you are calling your API from a React website, consider using the Connection generator to configure the client.
More Information
Section titled “More Information”For more information about tRPC, please refer to the tRPC documentation.
Connections
Section titled “Connections”Use the connection generator to integrate this project with others in your workspace. The following connections involve this project: