Skip to main content

Cloud and deployment · Intermediate · 20 min

Write, test and deploy an AWS Lambda function in Node.js

By Padding · Updated 18 Nov 2026
Node.js 26.13 · AWS CLI 2.42.4 · Lambda runtime nodejs26.x

You will have a tested Node.js 26 function running on AWS Lambda with its own logs-only role, tuned memory, timeout and environment variables, and a published version behind a live alias you can move forward or roll back.

On this page

AWS Lambda runs a function when something asks it to, and bills only for the time it runs. You hand it a zip file and a handler name, and AWS takes care of the servers, the operating system and the Node.js install. What you still own is the code, its tests, the permissions it runs with and how you release new versions of it.

In this tutorial you build order-total, a small function that receives a shopping basket as JSON and returns the subtotal, VAT and total. You test it on your laptop with Node's built-in test runner before AWS ever sees it, package it, and deploy it with the AWS CLI on the newest Node.js runtime, nodejs26.x. It runs with a role that can write to its own log group and nothing else. Then you tune memory, timeout and environment variables, publish an immutable version, and point a live alias at it so callers never depend on whatever you deployed last.

Cost. Lambda's pricing page (checked 26 November 2026) lists a free tier of one million requests and 400,000 GB-seconds of compute a month. The few invocations here fit comfortably inside it. Log storage in CloudWatch is billed separately, which is why you set a retention period, and the last step deletes everything.

Files live in ~/lambda-demo and AWS names start with order-total, so nothing collides with what your account already has.

Step 1 · Write the handler

Create the project. package.json gives you an npm test command and nothing else: the function has no dependencies, so there is no node_modules to ship.

Bash
mkdir -p ~/lambda-demo/test
cd ~/lambda-demo
cat > package.json <<'JSON'
{
  "name": "order-total",
  "private": true,
  "scripts": {
    "test": "node --test"
  }
}
JSON

Now the function itself, in index.mjs. The .mjs extension tells Node.js, and Lambda, that this is an ES module, so export and import work without any extra setting:

Bash
cat > index.mjs <<'JS'
// Work in minor units (cents, kobo, pence) so 0.1 + 0.2 problems never reach a price.
const toMinor = (amount) => Math.round(amount * 100);

export function quote(items, { vatRate = 0, currency = 'USD' } = {}) {
  if (!Array.isArray(items) || items.length === 0) {
    throw new Error('items must be a non-empty array');
  }
  let subtotal = 0;
  for (const item of items) {
    const validQty = Number.isInteger(item?.qty) && item.qty > 0;
    const validPrice = typeof item?.price === 'number' && item.price >= 0;
    if (!validQty || !validPrice) {
      throw new Error(`invalid item: ${JSON.stringify(item)}`);
    }
    subtotal += toMinor(item.price) * item.qty;
  }
  const vat = Math.round((subtotal * vatRate) / 100);
  return { currency, subtotal: subtotal / 100, vat: vat / 100, total: (subtotal + vat) / 100 };
}

export const handler = async (event, context) => {
  const vatRate = Number(process.env.VAT_RATE ?? '0');
  if (Number.isNaN(vatRate)) {
    throw new Error('VAT_RATE must be a number');
  }
  const currency = process.env.CURRENCY ?? 'USD';
  const result = quote(event?.items, { vatRate, currency });
  console.log(JSON.stringify({
    msg: 'quoted',
    requestId: context?.awsRequestId,
    items: event.items.length,
    total: result.total,
  }));
  return result;
};
JS

Three choices here matter on Lambda:

  • The logic is a plain function. quote knows nothing about Lambda, so you can test it, and reuse it, without faking AWS. handler is a thin layer that reads settings, calls quote and logs.
  • The handler is async. Lambda waits for the returned promise and sends its value back to the caller. A thrown error becomes a failed invocation. From Node.js 24 onwards Lambda no longer supports the older (event, context, callback) style, so async is the only form worth learning.
  • Settings come from environment variables, read on every call. The same zip can then run with different VAT rates or currencies, and nothing about the business rules is baked into the code.

The log line is JSON on purpose. CloudWatch stores whatever you print, and one JSON object per line is easy to search later.

Check it worked

ls ~/lambda-demo shows index.mjs, package.json and test. node --check index.mjs prints nothing, which means the file parses.

Bash
node --check index.mjs && echo "index.mjs parses"

Step 2 · Test it locally with node --test

A Lambda handler is a function that takes an event object and returns a value, so a unit test can call it directly with a sample event. Write three tests: the arithmetic, the environment variables, and a bad request:

Bash
cat > test/index.test.mjs <<'JS'
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { handler, quote } from '../index.mjs';

const event = {
  items: [
    { sku: 'rice-5kg', price: 12.5, qty: 2 },
    { sku: 'oil-1l', price: 3.2, qty: 1 },
  ],
};

test('adds up items in minor units', () => {
  assert.deepEqual(quote(event.items), { currency: 'USD', subtotal: 28.2, vat: 0, total: 28.2 });
});

test('handler reads VAT and currency from the environment', async () => {
  process.env.VAT_RATE = '7.5';
  process.env.CURRENCY = 'NGN';
  try {
    const result = await handler(event, { awsRequestId: 'local-test' });
    assert.deepEqual(result, { currency: 'NGN', subtotal: 28.2, vat: 2.12, total: 30.32 });
  } finally {
    delete process.env.VAT_RATE;
    delete process.env.CURRENCY;
  }
});

test('handler rejects an empty basket', async () => {
  await assert.rejects(handler({ items: [] }, {}), /non-empty array/);
});
JS
npm test

node --test finds files that end in .test.mjs on its own. The second test passes a fake context with only the one field the handler reads. Note 3.2 * 100 is 320.00000000000006 in JavaScript; toMinor rounds it to 320 before anything is added up.

Check it worked

The summary at the end shows ℹ pass 3 and ℹ fail 0. You also see the JSON log line from the second test, with "total":30.32. If a test fails, Node prints the expected and actual objects side by side.

Step 3 · Package the function as a zip

Lambda takes the code as a zip whose top level holds the handler file. Package only what runs: the tests and package.json stay out. Write a sample event for later at the same time:

Bash
cd ~/lambda-demo
rm -f function.zip
zip function.zip index.mjs
cat > event.json <<'JSON'
{
  "items": [
    { "sku": "rice-5kg", "price": 12.5, "qty": 2 },
    { "sku": "oil-1l", "price": 3.2, "qty": 1 }
  ]
}
JSON
unzip -l function.zip

A function with npm dependencies ships its node_modules folder in the same zip, next to index.mjs. Keep the package small: Lambda downloads and unpacks it whenever it starts a fresh copy of your function, so a large zip slows those cold starts. On a slow or metered connection, a few kilobytes also uploads much faster than a bundle full of packages you do not use.

Check it worked

unzip -l lists exactly one file, index.mjs, at the top level with no folder in front of it. If you see lambda-demo/index.mjs, you zipped from the wrong folder and Lambda will not find the handler.

Step 4 · Create a log group and a logs-only execution role

When Lambda runs your function, it acts as an execution role. Whatever that role may do, your code may do. This function only writes logs, so the role gets exactly that.

Pick a Region and keep the account ID and names in variables. Replace eu-west-2 with the Region you want; for users in southern Africa, Cape Town (af-south-1) is an option, but it is an opt-in Region that you enable in the account settings first:

Bash
cd ~/lambda-demo
export AWS_DEFAULT_REGION=eu-west-2   # replace with your Region
REGION="$AWS_DEFAULT_REGION"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
FUNCTION=order-total
ROLE=order-total-lambda
LOG_GROUP="/aws/lambda/${FUNCTION}"
echo "$ACCOUNT_ID $REGION $LOG_GROUP"

Lambda writes to a log group named /aws/lambda/<function name>. Create it yourself rather than letting Lambda do it on the first call. That way you set how long logs are kept (by default CloudWatch keeps them for ever, and you pay for storage for ever), and the role does not need permission to create log groups:

Bash
aws logs create-log-group --log-group-name "$LOG_GROUP"
aws logs put-retention-policy --log-group-name "$LOG_GROUP" --retention-in-days 14

The trust policy says who may use the role: only the Lambda service.

Bash
cat > trust.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "lambda.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
JSON
ROLE_ARN=$(aws iam create-role --role-name "$ROLE" \
  --assume-role-policy-document file://trust.json \
  --query Role.Arn --output text)
echo "$ROLE_ARN"

The permissions policy lets the role create log streams and write events in this one log group. The heredoc is unquoted so the shell fills in your Region and account ID:

Bash
cat > logs-policy.json <<JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "WriteOwnLogGroupOnly",
      "Effect": "Allow",
      "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "arn:aws:logs:${REGION}:${ACCOUNT_ID}:log-group:${LOG_GROUP}:*"
    }
  ]
}
JSON
aws iam put-role-policy --role-name "$ROLE" \
  --policy-name write-own-logs \
  --policy-document file://logs-policy.json

The AWS managed policy AWSLambdaBasicExecutionRole would also work, but it allows writing to any log group in the account and creating new ones. The inline policy above is the same idea cut down to one function. The trade-off: if someone deletes the log group, this role cannot recreate it and the function's logs stop arriving, so recreate the group with the two aws logs commands above.

Check it worked

echo "$ROLE_ARN" prints something like arn:aws:iam::123456789012:role/order-total-lambda. aws iam list-role-policies --role-name "$ROLE" lists write-own-logs, and aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[0].retentionInDays' prints 14.

Bash
aws iam list-role-policies --role-name "$ROLE" --query 'PolicyNames' --output text | grep -Fx write-own-logs
aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[0].retentionInDays' --output text | grep -Fx 14

Step 5 · Deploy with create-function

IAM changes take a few seconds to reach every AWS service, and a brand-new role is often not yet usable by Lambda. Wait ten seconds, then create the function:

Bash
sleep 10
aws lambda create-function \
  --function-name "$FUNCTION" \
  --runtime nodejs26.x \
  --architectures arm64 \
  --handler index.handler \
  --role "$ROLE_ARN" \
  --zip-file fileb://function.zip \
  --query '{Arn:FunctionArn,State:State}'
aws lambda wait function-active-v2 --function-name "$FUNCTION"
  • --handler index.handler means "the export called handler in the file index.mjs".
  • --runtime nodejs26.x is the newest Node.js runtime. Lambda adds a runtime only once that Node.js line reaches long-term support, and publishes a deprecation date for each, so check the runtimes page once a year.
  • --architectures arm64 runs the function on AWS Graviton processors. Plain JavaScript runs the same on either architecture; packages with native code must be built for the one you choose.
  • fileb:// sends the file as raw bytes. Plain file:// would read it as text and break the zip.

If create-function fails with The role defined for the function cannot be assumed by Lambda, the role has not propagated yet. Wait another ten seconds and run the same command again.

Check it worked

wait function-active-v2 returns with no output once the function is ready. Then ask for its settings:

Bash
aws lambda get-function-configuration --function-name "$FUNCTION" \
  --query '[Runtime,Handler,State,MemorySize,Timeout]' --output text

It prints nodejs26.x, index.handler, Active, 128 and 3: the defaults are 128 MB of memory and a 3-second timeout, which you change in a later step.

Step 6 · Invoke it and read the logs

Send the sample event and save the reply to response.json:

Bash
aws lambda invoke --function-name "$FUNCTION" \
  --payload fileb://event.json \
  response.json
cat response.json

The CLI prints "StatusCode": 200 and "ExecutedVersion": "$LATEST". response.json holds {"currency":"USD","subtotal":28.2,"vat":0,"total":28.2}, the same result as the first unit test.

Now send a basket with nothing in it:

Bash
echo '{"items": []}' > empty.json
aws lambda invoke --function-name "$FUNCTION" --payload fileb://empty.json error.json
cat error.json

The status code is still 200, because the invocation itself worked, but the output adds "FunctionError": "Unhandled". error.json holds an errorType of Error and the errorMessage items must be a non-empty array. Code that calls Lambda must check FunctionError, not only the status code.

Read the logs from the last ten minutes:

Bash
aws logs tail "$LOG_GROUP" --since 10m

Check it worked

The output shows one block per invocation: a START RequestId: ... line, your JSON quoted line with the same request ID, an END line and a REPORT line. REPORT gives the duration, the billed duration, the memory size and the maximum memory used, and on a cold start an Init Duration. The failed call shows the error and stack trace instead of the quoted line. Logs can take a few seconds to appear; run tail again if the list is empty.

Step 7 · Set memory, timeout and environment variables

Change three settings at once: 256 MB of memory, a 10-second timeout, and two environment variables the handler reads:

Bash
aws lambda update-function-configuration --function-name "$FUNCTION" \
  --memory-size 256 \
  --timeout 10 \
  --environment 'Variables={CURRENCY=NGN,VAT_RATE=7.5}' \
  --query 'LastUpdateStatus'
aws lambda wait function-updated-v2 --function-name "$FUNCTION"
  • Memory goes from 128 MB to 10,240 MB, and Lambda gives the function CPU in proportion to it. A function that spends its time computing can finish faster, and sometimes cheaper, with more memory. The Max Memory Used figure in the REPORT log line tells you how much this one needs.
  • Timeout can be up to 900 seconds. Set it a little above the slowest run you expect, so a stuck call fails quickly instead of billing for minutes.
  • Environment variables replace the whole set each time; any variable you leave out of --environment is removed. Anyone who can read the function's configuration can read them, so they are for settings like these, never for passwords or API keys. Keep secrets in AWS Secrets Manager or Parameter Store and give the role permission to read just that one secret.

Check it worked

Bash
aws lambda get-function-configuration --function-name "$FUNCTION" \
  --query '[MemorySize,Timeout,Environment.Variables.CURRENCY,Environment.Variables.VAT_RATE]' --output text

It prints 256, 10, NGN and 7.5. Invoking with event.json again now returns "currency":"NGN", "vat":2.12 and "total":30.32, matching the second unit test.

Step 8 · Publish a version and point an alias at it

So far every change has gone straight to $LATEST, the editable copy. Anything that calls $LATEST gets your changes the moment you make them, including mistakes. A version is a frozen snapshot of the code and configuration together, numbered 1, 2, 3 and never changed again. An alias is a named pointer to one version, and it is what callers should use.

Publish version 1 and point an alias called live at it:

Bash
V1=$(aws lambda publish-version --function-name "$FUNCTION" \
  --description "VAT 7.5 percent, NGN" --query Version --output text)
echo "published version $V1"
aws lambda create-alias --function-name "$FUNCTION" \
  --name live --function-version "$V1" --query AliasArn --output text

Callers use the alias ARN, which ends in :live, or pass --qualifier live:

Bash
aws lambda invoke --function-name "$FUNCTION" --qualifier live \
  --payload fileb://event.json live.json
cat live.json

Now ship a change. Say the VAT rate moves to 8 percent. Change $LATEST, publish version 2, and only then move the alias:

Bash
aws lambda update-function-configuration --function-name "$FUNCTION" \
  --environment 'Variables={CURRENCY=NGN,VAT_RATE=8}' --query 'LastUpdateStatus'
aws lambda wait function-updated-v2 --function-name "$FUNCTION"
V2=$(aws lambda publish-version --function-name "$FUNCTION" \
  --description "VAT 8 percent, NGN" --query Version --output text)
aws lambda get-function-configuration --function-name "$FUNCTION" --qualifier live \
  --query 'Environment.Variables.VAT_RATE' --output text
aws lambda update-alias --function-name "$FUNCTION" \
  --name live --function-version "$V2" --query FunctionVersion --output text

The get-function-configuration call reads through the alias before the switch and prints 7.5: publishing version 2 changed nothing for callers of live. update-alias then prints 2. A code change works the same way: rebuild function.zip, run aws lambda update-function-code --function-name order-total --zip-file fileb://function.zip, wait with function-updated-v2, then publish and move the alias.

If version 2 misbehaves, rolling back is one command, and no rebuild:

Bash
aws lambda update-alias --function-name "$FUNCTION" \
  --name live --function-version "$V1" --query FunctionVersion --output text

Check it worked

The rollback prints 1. Then confirm where live points and what it runs with:

Bash
aws lambda get-alias --function-name "$FUNCTION" --name live --query FunctionVersion --output text
aws lambda get-function-configuration --function-name "$FUNCTION" --qualifier live \
  --query 'Environment.Variables.VAT_RATE' --output text

The first line is 1 and the second 7.5. aws lambda list-versions-by-function --function-name order-total --query 'Versions[].Version' lists $LATEST, 1 and 2.

Step 9 · Clean up

The next commands delete the function, every version and alias, its logs and its role. If you plan to follow the API Gateway tutorial with this function, stop here and come back later.

Bash
aws lambda delete-function --function-name "$FUNCTION"
aws logs delete-log-group --log-group-name "$LOG_GROUP"
aws iam delete-role-policy --role-name "$ROLE" --policy-name write-own-logs
aws iam delete-role --role-name "$ROLE"
cd ~
rm -rf ~/lambda-demo

Deleting the function without a qualifier removes all its versions and aliases with it. The role goes last, after the function that used it.

Check it worked

Bash
aws lambda list-functions --query "Functions[?FunctionName=='order-total'].FunctionName" --output text
aws iam list-roles --query "Roles[?RoleName=='order-total-lambda'].RoleName" --output text

Both commands print nothing.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.