Overriding Node.js Runtime in AWS CDK v1 Lambda Functions
AWS CDK v1 has a hard limitation where Lambda functions are restricted to Node.js 16.x runtime, even though AWS Lambda supports newer versions like Node.js 18.x and 20.x. If you’re not ready to migrate to CDK v2 but need to use a newer Node.js runtime, you can use CDK’s escape hatch mechanism to override the runtime property.
The Problem
CDK v1 was designed when Node.js 16 was the latest supported runtime. Even though AWS Lambda now supports Node.js 18.x and 20.x, CDK v1 constructs don’t expose these newer runtimes as options. This leaves you with two choices: migrate to CDK v2 or find a workaround.
The Solution
You can use CDK’s property override feature to directly modify the CloudFormation properties of your Lambda functions:
import * as lambda from '@aws-cdk/aws-lambda';
import { CfnFunction } from '@aws-cdk/aws-lambda';
export class MyStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// Create Lambda function with CDK v1's limited runtime options
const myFunction = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_16_X, // CDK v1 limitation
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda'),
});
// Override the runtime to use Node.js 20.x
this.applyRuntimeOverride(myFunction, 'nodejs20.x');
}
private applyRuntimeOverride(func: lambda.Function, runtime: string) {
// Access the underlying CloudFormation resource
const cfnFunction = func.node.defaultChild as CfnFunction;
// Override the Runtime property
cfnFunction.addPropertyOverride('Runtime', runtime);
}
}
For more complex scenarios with multiple functions, you can create a reusable runtime override utility:
interface LambdaSupportProps {
// Define your custom props if needed
}
interface HandlerOptions {
// Define handler options if needed
}
private createRuntimeOverride() {
return (f: lambda.Function, d: LambdaSupportProps, c: HandlerOptions) => {
// Apply Node.js 20.x runtime override for CDK v1
(f.node.defaultChild as CfnFunction).addPropertyOverride(
'Runtime',
'nodejs20.x'
);
};
}
How It Works
- CDK’s
addPropertyOverridemethod directly modifies the CloudFormation template - The override happens at synthesis time, before deployment
- CloudFormation receives the corrected runtime value and deploys accordingly
- Your Lambda function will run on the specified Node.js runtime despite CDK v1’s limitations
This approach bypasses CDK’s runtime validation while maintaining the benefits of Infrastructure as Code.
Important Notes
- This is an escape hatch that bypasses CDK’s type safety
- Ensure the runtime you specify is supported by AWS Lambda
- Test thoroughly since you’re working outside CDK’s intended constraints
- Consider migrating to CDK v2 for long-term projects, as it natively supports newer runtimes
- The override must be applied after the Lambda function is created but before synthesis