AWS Lambda support Node.js 18 now. Should we update the version of Node.js in the Lambda runtime?
Tags: serverless, lambda
Published: 2022-11-30 03:18:04


Recently, AWS Lambda announced that it supports Node.js 18 and it is available in all AWS regions. This is a big news for Node.js developers. It means that we can use the latest version of Node.js in AWS Lambda. However, should we update the version of Node.js in the Lambda runtime? Let's find out.

## Why we should update the version of Node.js in the Lambda runtime?

The reason is simple. The new version of Node.js has new features and bug fixes. We should always use the latest version of Node.js in the Lambda runtime. Besides, the new version of Node.js is faster and more secure. It is a good idea to update the version of Node.js in the Lambda runtime.

Some of benefits of using the latest version of Node.js in the Lambda runtime:

### Support ES2021 features

Node.js 18 supports ES2021 features. We can use them in the Node.js runtime environment. For example, we can use the optional chaining operator (?.) and the nullish coalescing operator (??).

```js
// index.mjs
export async function handler(event, context) {
  const data = {
    foo: {
      bar: 'baz',
    },
  }
  const value = data?.foo?.bar ?? 'default'
  return value
}
```

### Support top-level await

Node.js 18 supports top-level await. We can use it in the Node.js runtime environment. For example, we can use it to make HTTP requests. I really like this feature because it really useful when we want to re-use same initialization code in multiple Lambda invocations. We can use top-level await to initialize the code once and then re-use it in multiple Lambda invocations.

```js
// index.mjs
const response = await fetch('https://example.com')
const data = await response.json()

export async function handler(event, context) {
  return data
}
```

### AWS SDK v3 support in the Node.js runtime environment

Lambda supports AWS SDK v3 in the Node.js runtime environment. This enables us to use the new AWS SDK v3 in the Node.js runtime environment. We can use the new AWS SDK v3 to make AWS API calls in the Node.js runtime environment. For example, we can use the new AWS SDK v3 to make DynamoDB API calls in the Node.js runtime environment without include the AWS SDK v3 in the Lambda deployment package.

```js
// index.mjs
import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb'
```

This is a big news for Node.js developers. We can use the new AWS SDK v3 to make AWS API calls in the Node.js runtime environment. We don’t need to use the old AWS SDK v2 anymore. This especially useful when creating functions in the AWS console or [inline code in the CloudFormation template](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html).

### Node.js 18 language updates

The Lambda Node.js 18 runtime also enables you to take advantage of new [Node.js 18 language features](https://github.com/nodejs/node/blob/main/doc/changelogs/CHANGELOG_V18.md). This includes improved performance for class fields and private class methods, JSON import assertions, and experimental features such as the Fetch API, [Test Runner module](https://github.com/nodejs/node/blob/main/doc/changelogs/CHANGELOG_V18.md#test-runner-module-experimental), and [Web Streams API](https://github.com/nodejs/node/blob/main/doc/changelogs/CHANGELOG_V18.md#web-streams-api-experimental).

#### JSON import assertion

The import assertions feature allows module import statements to include additional information alongside the module specifier. Now the following code is valid:

```js
// index.mjs

// static import with JSON import assertion
import fooData from './foo.json' assert { type: 'json' }

// dynamic import with JSON import assertion
const { default: barData } = await import('./bar.json', { assert: { type: 'json' } })

export const handler = async (event) => {
  console.log(fooData)
  // logs data in foo.json file
  console.log(barData)
  // logs data in bar.json file

  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  }
  return response
}
```

#### Support fetch API in the Node.js runtime environment

The fetch API is a standard API for making HTTP requests in the browser. It is also available in Node.js 16 and above. We can use it to make HTTP requests in the Node.js runtime environment. It is a standard API and we don’t need to install any third-party libraries to use it.
In a previous article, I wrote about how to use the fetch API in the Node.js runtime environment. [You can read it here.](https://www.codewithyou.com/blog/finally-we-can-use-fetch-api-in-nodejs)

```js
// index.mjs
export async function handler(event, context) {
  const response = await fetch('https://example.com')
  const data = await response.json()
  return data
}
```

## How to update the version of Node.js in the Lambda runtime?

We can update the version of Node.js in the Lambda runtime by using the AWS CDK. The following code shows how to update the version of Node.js in the Lambda runtime.

```typescript
import * as lambda from '@aws-cdk/aws-lambda'

const lambdaFunction = new lambda.Function(this, 'LambdaFunction', {
  runtime: lambda.Runtime.NODEJS_18_X,
  handler: 'index.handler',
  code: lambda.Code.fromAsset('lambda'),
})
```

Or we can update the version of Node.js in the Lambda runtime by using the AWS CloudFormation. The following code shows how to update the version of Node.js in the Lambda runtime.

```yaml
Resources:
  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: nodejs18.x
      Handler: index.handler
      Code:
        ZipFile: |
          exports.handler = async (event) => {
            return {
              statusCode: 200,
              body: JSON.stringify('Hello from Lambda!'),
            };
          };
```

## Conclusion

Node.js 18 is now supported by Lambda. We should consider updating the version of Node.js to Node.js 18 in the Lambda runtime as soon as possible. For existing Node.js functions, review your [code for compatibility with Node.js 18](https://nodejs.org/de/blog/announcements/v18-release-announce/), including deprecations, then migrate to the new runtime by changing the function’s runtime configuration to nodejs18.x.


Thanks for reading. If you have any questions, please leave a comment below. If you like this article, please share it with your friends. You can also follow me on [Twitter](https://twitter.com/bvbinh) and [LinkedIn](https://www.linkedin.com/in/binhbv).