A monorepo pattern for frontend, backend, and infrastructure-as-code, with Nx’s task graph deciding what must rebuild before CDK deploy.
In a recent project I used an Nx monorepo containing the entirety of a full stack web application: a web frontend, a backend built on AWS Lambda functions behind HTTP API Gateway, and infrastructure-as-code written in TypeScript using AWS CDK.
This post outlines how I used Nx as the sole orchestrator for the entire SDLC, so that building and deploying the entire app end-to-end was as simple as running onenx CLI command.
The problem: manual deploy ordering
cdk deploy only updates CloudFormation. It does not build your application. Built assets must already be on disk; for example, build the web app, build each Lambda project, and so on, then run cdk deploy.
Without a single task orchestrator, deploy becomes a checklist or shell script you maintain by hand:
Build the web app so its assets exist under something like dist/apps/web-app/.
Build each function or service project your constructs reference—one entry in the checklist per Code.fromAsset (or similar) path. In the examples below that is a single project, api-handler, with build output under dist/apps/api-handler/; a finer-grained API might list many sibling projects instead.
Compile the CDK app (or run it directly with ts-node at deploy time)
Run cdk deploy from the infra app directory with the right account and environment.
Steps 1 and 2 are easy to skip when you are “only changing infra.” Your CDK constructs point at directories on the filesystem—via Code.fromAsset(...), Source.asset(...), etc.,—which must contain the compiled sources to deploy. These directories could contain stale or invalid content because nothing in the CDK CLI enforced that those dist folders were fresh first.
By setting up the CDK app as a first-class project in an Nx monorepo, we can leverage the power of the Nx task graph so that one deploy command pulls in everything that must run first. You just invoke the deploy target for the CDK app and Nx automatically runs the dependency targets (asset builds, then the CDK app build) before cdk deploy runs:
Asset projects build in parallel where the graph allows, then infra:build compiles the TypeScript CDK app to JavaScript; only after that does infra:deploy invoke the CDK CLI. The same build prerequisite applies to infra:synth when you run synth on its own.
This is particularly powerful when combined with Nx's output caching, as Nx will only rebuild the dependencies it needs to on a redeploy.
Project layout
The examples below use a simple fictional repo containing a frontend web app, a single monolith Lambda for the backend API, plus an infra project for the CDK app:
apps/
infra/ # CDK app
web-app/ # website; compiles to dist/apps/web-app/
api-handler/ # lambda; compiles to dist/apps/api-handler/
libs/
[various libs] # Non-buildabble libs imported by app projects as needed.
# E.g., you may want to decompose your web app into feature-specifc
# modules with one lib per feature, or create a shared lib containing
# types for your the REST API request/response bodies that you can
# import in both the web app and the lambdas
A real monorepo might have multiple lambda functions like users-handler, orders-handler, and so on. Just make one Nx project per lambda.
You don't necessarily need to use the apps & libs directory layout, but I prefer to put any project with a build target that creates a single deployable artefact under apps, and everything else under libs.
Build the CDK app with esbuild
The infra project is just treated as any other Nx node app. The CDK app is compiled with @nx/esbuild:esbuild so a deploy runs the compiled JavaScript under dist/apps/infra, not the source with ts-node.
The build target in apps/infra/project.json should look something like this:
dependsOn: ["^build"] means upstream projects the CDK app depends on in the project graph build first. This means if we specify the web app and lambda projects as dependencies of this infra project, Nx will build those first, before building the infra app (more on that later).
The CDK config in apps/infra/cdk.json should point at the build output, relative to the infra project root dir (apps/infra):
deploy and synth operations can be set up as targets in the infra app's project.json file using the nx:run-commands executor to invoke the cdk CLI. The executor should be configured with cwd: "{projectRoot}" so it picks up cdk.json in that directory:
dependsOn: ["build"] on both targets ensures the build target for the infra project (and in turn anything build itself depends on) is executed before CDK runs. This task dependency chain is the magic that lets us run one simple nx run infra:deploy:production command and not need to care about explicitly building all the dependencies manually beforehand.
The example above has two environments for illustrative purposes: production and staging. We use configurations for the deploy target to control which environment we are deploying to. Each of those configurations sets the DEPLOY_ENV environment variable for the target to a specific value. The CDK app reads that variable when invoked via cdk deploy and selects stack or construct settings based on its value. For example, you might create a function like this:
functiongetEnvironmentConfig(){if(process.env['DEPLOY_ENV']==='production'){return{
domain:APEX_DOMAIN,// any other environment-specific config for prod env}}if(process.env['DEPLOY_ENV']==='staging'){return{
domain:`staging.${APEX_DOMAIN}`,// any other environment-specific config for staging env}}// any other supported environment types here...// ...then finally fail when no valid value for DEPLOY_ENV was matchedthrownewError(`Invalid DEPLOY_ENV value: ${deployEnv}`);}
What must build before deploy?
The CDK app source doesn't contain any import statements from the web app or lambda projects, so Nx doesn't automatically which projects the infra app depends on. We therefore need to list every project whose build output is consumed by infra explicitly as dependencies of the infra project or its build target. There are two patterns for this:
Pattern A — implicitDependencies plus the default task graph
Implicit dependencies tells Nx "this project consumes outputs from these projects". With build.dependsOn: ["^build"], Nx runs each listed project's build before infra:build, and deploy waits on infra:build. This is what I use today: one place to list consumers, no duplicate task lists—add a new Lambda project to the array when you add a stack that packages it.
Pattern B — explicit cross-project dependsOn in deploy
Constructs in the CDK app should read absolute dist paths, not paths relative to the CDK TypeScript source file. We can use @nx/devkit's workspaceRoot (which is the absolute path to the root dir of the monorepo) to keep this portable across machines. Each function (or other asset) has its output dir appended to the workspace root to get the full path:
By making the CDK app an Nx project in our monorepo, we can define Nx targets for it that wrap CDK CLI commands and bake in dependencies on the other projects in the monorepo whose build output we want to deploy to our CDK stacks.
After making changes to any of the projects, we can run one single nx run infra:deploy:<configuration> command to rebuild anything that's changed and redeploy to our target environment. Nx knows what needs to be rebuilt and what can be reused from its cache based on what's changed, keeping the rebuild time to a minimum and removing the mental overhead of having to figure out what to rebuild for ourselves.
Support
If you've found my blog useful, please consider buying me a coffee to say thanks: