DEV Community

Zeke Sebulino
Zeke Sebulino

Posted on

Verify if your code is running in AWS Lambda / Serverless

Are you developing a Node.js app to be deployed on AWS Lambda? If so, you may need to detect whether your code is running in the AWS Lambda environment or not. One way to do this is by examining the LAMBDA_TASK_ROOT environment variable. In this post, we'll explore how you can use this variable to detect if your Node.js app code is running on AWS Lambda.

What is LAMBDA_TASK_ROOT?

LAMBDA_TASK_ROOT is an environment variable that is automatically set by AWS Lambda for all Node.js functions. This variable contains the path to the directory where the code for the Lambda function is located. In other words, it points to the root directory of the Lambda function.

How to detect if your code is running on AWS Lambda?

To check if your Node.js app code is running on AWS Lambda, you can examine the LAMBDA_TASK_ROOT environment variable. Here's an example:

if (process.env.LAMBDA_TASK_ROOT) {
  // Running on AWS Lambda
} else {
  // Not running on AWS Lambda
}
Enter fullscreen mode Exit fullscreen mode

This code checks if the LAMBDA_TASK_ROOT environment variable is set. If it is, it assumes that the code is running on AWS Lambda. If it's not set, it assumes that the code is not running on AWS Lambda.

It's important to note that this method is not foolproof. In some cases, the LAMBDA_TASK_ROOT environment variable may not be set even if the code is running on AWS Lambda. However, for most cases, it should be reliable.

If you encounter any issues, you can explore other environment variables that are set by AWS Lambda, such as AWS_LAMBDA_FUNCTION_NAME, AWS_REGION, and AWS_EXECUTION_ENV, among others.

Top comments (0)