profile picture

@clementvial

I'm a full Stack JavaScript developer from Canada ðŸ‡¨ðŸ‡¦ Building with TypeScript, React, AI/ML & more.

Check out my links and posts

Overriding Node.js Runtime in AWS CDK v1 Lambda Functions

CDK v1 locks you into Node.js 16.x for Lambda functions, even though AWS Lambda supports Node.js 18 and 20. Not ready to migrate to CDK v2? Here’s the workaround.

Use addPropertyOverride to modify the CloudFormation template directly:

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);
}
}

This modifies the CloudFormation template at synthesis time. Create the function with NODEJS_16_X (to keep CDK happy), then override it to nodejs20.x before deployment.

For multiple functions, make it reusable:

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'
);
};
}

Quick notes: this bypasses CDK’s type safety, so verify the runtime actually exists in AWS Lambda and test thoroughly. For long-term projects, consider migrating to CDK v2, it supports newer runtimes natively.