Skip to content

TypeScript DynamoDB

This generator creates a new TypeScript DynamoDB project backed by Amazon DynamoDB, using ElectroDB for type-safe entity modelling. It generates the application code and infrastructure needed to provision and manage a DynamoDB table using AWS CDK or Terraform, with single-table design support and built-in local development via DynamoDB Local.

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

pnpm nx g @aws/nx-plugin:ts#dynamodb
Build your command8

Required

Generator Options8 options
nameRequiredstring

Name of the DynamoDB project to generate

directorystringDefault: packages

The directory to store the project in.

frameworkenumDefault: electrodb

The framework to use for DynamoDB entities.

electrodb
infraenumDefault: dynamodb

Infrastructure to provision for the DynamoDB table.

dynamodbnone
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.

tableNamestring

The DynamoDB table name. Auto-generated if not specified.

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 creates the following project structure in the <directory>/<name> directory:

  • Directorysrc
    • index.ts Project entry point and exports
    • client.ts DynamoDB client singleton and table name resolution
    • Directoryentities
      • example.ts Example ElectroDB entity definition
      • index.ts Entity exports
  • config.json Table configuration including GSI definitions and local development settings
  • package.json Project manifest defining the project’s package name and dependencies
  • project.json Project configuration and build targets

The local development scripts are shared across all DynamoDB projects (both TypeScript and Python) and generated once into:

  • Directorypackages/common/scripts/src/dynamodb
    • create-local-table.ts Creates the DynamoDB table in the local DynamoDB Local instance
    • pull-image.ts Pulls the DynamoDB Local image
    • start-container.ts Starts the DynamoDB Local container

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/constructs/src
    • Directoryapp
      • Directorydynamodb
        • <name>.ts Infrastructure specific to your table
    • Directorycore
      • dynamodb.ts Generic DynamoDB table construct

The deployed project provisions the table itself, which any project it is connected to reads and writes:

Loading the diagram…

The generator configures a dev target that starts a DynamoDB Local instance and creates the table. Use the project’s dev target:

Terminal window
pnpm nx dev <project-name>

This automatically:

  1. Pulls the DynamoDB Local image (pull-image target)
  2. Starts a container
  3. Creates a local table with the indexes defined in config.json

The generated project uses ElectroDB for type-safe entity modelling on a single DynamoDB table, following DynamoDB’s single-table design. Add or update entity files under src/entities/, using the generated example entity as a starting point.

Example entity definition:

packages/my-table/src/entities/example.ts
import { Entity } from 'electrodb';
import { getDynamoDBClient, resolveTableName } from '../client.js';
export const createExampleEntity = async () =>
new Entity(
{
model: {
entity: 'example',
version: '1',
service: 'MyTable',
},
attributes: {
id: {
type: 'string',
required: true,
},
createdAt: {
type: 'string',
required: true,
default: () => new Date().toISOString(),
readOnly: true,
},
updatedAt: {
type: 'string',
required: true,
default: () => new Date().toISOString(),
watch: '*',
set: () => new Date().toISOString(),
},
},
indexes: {
primary: {
pk: {
field: 'pk',
composite: ['id'],
},
sk: {
field: 'sk',
composite: [],
},
},
},
},
{ client: getDynamoDBClient(), table: await resolveTableName() },
);

For more details, see the ElectroDB entity documentation.

The generated src/client.ts exports two key utilities:

  • getDynamoDBClient() — returns a cached singleton DynamoDBClient. When LOCAL_DEV=true, connects to the local DynamoDB Local instance; otherwise creates an AWS client using the default credential chain.
  • resolveTableName() — returns the DynamoDB table name. When LOCAL_DEV=true, returns the local table name constant; otherwise fetches the name from AWS AppConfig using the RUNTIME_CONFIG_APP_ID environment variable and caches it for subsequent calls.

Stopping dev (e.g. with Ctrl+C) automatically removes the DynamoDB Local container, but preserves the named volume so your data persists across restarts.

GSIs are defined in config.json at the project root under the tableConfig.globalSecondaryIndexes key. Add an entry for each GSI, following the single-table design naming convention for GSI keys:

config.json
{
...
"tableConfig": {
"globalSecondaryIndexes": [
{
"indexName": "gsi1pk-gsi1sk-index",
"partitionKey": "gsi1pk",
"sortKey": "gsi1sk"
},
{
"indexName": "gsi2pk-gsi2sk-index",
"partitionKey": "gsi2pk",
"sortKey": "gsi2sk"
}
]
}
}

The sortKey field is optional for hash-key-only GSIs.

This config file is the single source of truth read by all consumers:

  • Local developmentdev reads config.json and creates or updates the local table to match the GSI list
  • CDK — the construct reads config.json at synth time, so GSI changes are reflected on the next cdk deploy
  • Terraform — the module reads config.json at plan/apply time

In any TypeScript project, import entity factories from your DynamoDB package and use them directly:

import { createExampleEntity } from '@my-scope/my-table';
const entity = await createExampleEntity();
const result = await entity.query.primary({ id: '123' }).go();

Behind the scenes, createExampleEntity() calls resolveTableName() to fetch the table name from AWS AppConfig at runtime.

The DynamoDB generator creates CDK or Terraform infrastructure based on your selected iac.

The CDK construct is created in common/constructs. Example usage:

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

This provisions a DynamoDB table with:

  • pk (partition key) and sk (sort key), both String type
  • Global Secondary Indexes as defined in config.json
  • On-demand (PAY_PER_REQUEST) billing
  • Customer-managed KMS encryption with automatic key rotation
  • Point-in-time recovery enabled
  • Deletion protection enabled
  • Table name registered in Runtime Config under the dynamodb namespace in AWS AppConfig

The table is protected by two independent guards, so that turning off either one alone cannot delete your data:

  • deletionProtection, enforced by DynamoDB.
  • RemovalPolicy.RETAIN, enforced by CloudFormation, which leaves the table in place when it is removed from the stack.

Disable protection for environments where table deletion is expected, such as short-lived development or preview stacks.

packages/infra/src/stacks/application-stack.ts
import { RemovalPolicy } from 'aws-cdk-lib';
import { MyTable } from '@my-scope/common-constructs';
const table = new MyTable(this, 'Table', {
deletionProtection: false,
removalPolicy: RemovalPolicy.DESTROY,
});

The table defaults to on-demand (PAY_PER_REQUEST) billing. Switch to provisioned capacity for predictable, high-throughput workloads.

packages/infra/src/stacks/application-stack.ts
import { BillingMode } from 'aws-cdk-lib/aws-dynamodb';
import { MyTable } from '@my-scope/common-constructs';
const table = new MyTable(this, 'Table', {
billingMode: BillingMode.PROVISIONED,
readCapacity: 5,
writeCapacity: 5,
});

Point-in-time recovery is enabled by default, allowing you to restore the table to any point in the last 35 days.

packages/infra/src/stacks/application-stack.ts
import { MyTable } from '@my-scope/common-constructs';
const table = new MyTable(this, 'Table', {
pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: false },
});

The table is encrypted with a customer-managed KMS key by default, created automatically for you. Switch to an AWS managed key, the AWS owned key, or bring your own KMS key, if you manage encryption differently.

Uses the shared aws/dynamodb KMS key that AWS manages on your behalf. It’s visible in your account’s KMS console and billed per request, but there’s no key for you to create, rotate or delete.

packages/infra/src/stacks/application-stack.ts
import { TableEncryption } from 'aws-cdk-lib/aws-dynamodb';
import { MyTable } from '@my-scope/common-constructs';
const table = new MyTable(this, 'Table', {
encryption: TableEncryption.AWS_MANAGED,
});

Uses a key fully owned and managed by AWS — free, with no key visible in your account at all. The simplest option when you don’t need a customer- or account-visible key for compliance reasons.

packages/infra/src/stacks/application-stack.ts
import { TableEncryption } from 'aws-cdk-lib/aws-dynamodb';
import { MyTable } from '@my-scope/common-constructs';
const table = new MyTable(this, 'Table', {
encryption: TableEncryption.DEFAULT,
});
iac = terraform

On an already-deployed table, changing encryption away from CUSTOMER_MANAGED (to either AWS_MANAGED or DEFAULT) in a single terraform apply fails: Terraform destroys the customer-managed key before updating the table, and DynamoDB then rejects the update because the key is already pending deletion.

Work around it by updating the table’s encryption directly via the AWS CLI first, then letting Terraform catch up and clean up the orphaned key:

Terminal window
# For AWS_MANAGED:
aws dynamodb update-table --table-name <table-name> \
--sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=alias/aws/dynamodb
# For DEFAULT:
aws dynamodb update-table --table-name <table-name> --sse-specification Enabled=false
# Then wait for this to report ENABLED (or for SSEDescription to disappear, for DEFAULT):
aws dynamodb describe-table --table-name <table-name> --query Table.SSEDescription.Status

Then update encryption in your Terraform config and run terraform apply as normal — Terraform now only needs to destroy the already-unused key, with nothing left depending on it.

Provide an existing customer-managed key instead of having one created for you. The key must already grant the DynamoDB service the permissions it needs in its own key policy.

packages/infra/src/stacks/application-stack.ts
import { Key } from 'aws-cdk-lib/aws-kms';
import { MyTable } from '@my-scope/common-constructs';
const key = Key.fromKeyArn(this, 'Key', 'arn:aws:kms:us-east-1:111111111111:key/my-key-id');
const table = new MyTable(this, 'Table', {
encryptionKey: key,
});

When the table creates its own customer-managed KMS key (the default, and only when you haven’t provided your own key), that key has automatic key rotation enabled by default. Disable it if your security policy manages rotation externally.

packages/infra/src/stacks/application-stack.ts
import { MyTable } from '@my-scope/common-constructs';
const table = new MyTable(this, 'Table', {
enableKeyRotation: false,
});

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

tRPCAmazon DynamoDB
tRPC API to TypeScript DynamoDBConnect a tRPC API to a DynamoDB table
SmithyAmazon DynamoDB
Smithy API to TypeScript DynamoDBConnect a Smithy API to a DynamoDB table
Strands AgentsTypeScriptAmazon DynamoDB
TypeScript Agent to TypeScript DynamoDBConnect a TypeScript Agent to a DynamoDB table
Model Context ProtocolAmazon DynamoDB
MCP Server to TypeScript DynamoDBConnect a TypeScript MCP Server to a DynamoDB table