Skip to content

Metadata

The Metadata utility allows you to fetch data from the AWS Lambda Metadata Endpoint (LMDS). This can be useful for retrieving information about the Lambda function, such as the Availability Zone ID.

Getting started

Installation

Add the library to your project:

1
npm install @aws-lambda-powertools/commons

Usage

You can fetch data from the LMDS using the getMetadata function. For example, to retrieve the Availability Zone ID:

Tip

Metadata is cached for the duration of the Lambda execution, so subsequent calls to getMetadata will return the cached data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import { getMetadata } from '@aws-lambda-powertools/commons/utils/metadata';
import { Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger({ serviceName: 'serverlessAirline' });
const metadata = await getMetadata();

export const handler = async () => {
  const { AvailabilityZoneID: azId } = metadata;
  logger.appendKeys({ azId });
};

Available metadata

Property Type Description
AvailabilityZoneID string The AZ where the function is running (e.g., use1-az1)

Testing your code

The metadata endpoint is not available during local development or testing. To ease testing, the getMetadata function automatically detects when it's running in a non-Lambda environment and returns an empty object. This allows you to write tests without needing to mock the LMDS responses.

If instead you want to mock specific metadata values for testing purposes, you can do so by setting environment variables that correspond to the metadata endpoint and authentication token, as well as mocking the fetch function to return the desired metadata. Here's an example of how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {
  clearMetadataCache,
  getMetadata,
} from '@aws-lambda-powertools/commons/utils/metadata';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

describe('function: getMetadata', async () => {
  let fetchMock: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    vi.clearAllMocks();
    clearMetadataCache();
    fetchMock = vi.fn();
    vi.stubGlobal('fetch', fetchMock);
  });

  afterEach(() => {
    vi.unstubAllEnvs();
    vi.unstubAllGlobals();
  });

  it('fetches metadata and caches the response', async () => {
    // Prepare
    vi.stubEnv('AWS_LAMBDA_INITIALIZATION_TYPE', 'on-demand');
    vi.stubEnv('AWS_LAMBDA_METADATA_API', '127.0.0.1:1234');
    vi.stubEnv('AWS_LAMBDA_METADATA_TOKEN', 'test-token');

    const payload = { runtime: 'nodejs20.x' };
    fetchMock.mockResolvedValue({
      ok: true,
      json: vi.fn().mockResolvedValue(payload),
    });

    // Act
    const resultA = await getMetadata();
    const resultB = await getMetadata();

    // Assess
    expect(resultA).toEqual(payload);
    expect(resultB).toBe(resultA);
    expect(fetchMock).toHaveBeenCalledTimes(1);
    expect(fetchMock).toHaveBeenCalledWith(
      'http://127.0.0.1:1234/2026-01-15/metadata/execution-environment',
      expect.objectContaining({
        headers: {
          Authorization: 'Bearer test-token',
        },
        signal: expect.any(AbortSignal),
      })
    );
  });
});

We also expose a clearMetadataCache function that can be used to clear the cached metadata, allowing you to test different metadata values within the same execution context.