日本語

Using AWS Emulator from the Node.js SDK for JavaScript v3

​​AWS Emulator​Amazon S3,AWS SDK for JavaScript,Node.js,TypeScript

The AWS SDK for JavaScript v3 can point at AWS Emulator with the same environment variables as the AWS CLI. However, the emulator's certificate is not read through AWS_CA_BUNDLE, so you need to add one more setting, NODE_EXTRA_CA_CERTS for Node.js. This is the procedure for testing Node.js code that uses S3 and similar services locally or in CI without an AWS account. I also include the output from my test environment for the other settings the SDK for JavaScript needs (S3 on localhost, and the data- prefix added to hostnames).

Note

My test environment was Ubuntu 24.04 (x86_64), Node.js 22.23.4, AWS SDK for JavaScript v3 (@aws-sdk/client-s3 and the other packages at 3.1169.0), and AWS Emulator 1.0.385 (released November 14, 2026). I did not use an AWS account or credentials. I have not checked the behavior on real AWS. Where this article mentions real AWS, it relies on the official documentation. I have not tested the SDK running in a browser, the emulator running in Docker, or calls from Jest or Vitest.

Add NODE_EXTRA_CA_CERTS to the same environment variables as the AWS CLI

Install the emulator by following the official Linux instructions, and start it with aws-emulator -t off (-t off turns off telemetry). Install the SDK from npm. In this article I use the clients for S3, STS, and Cloud Map (client-servicediscovery), along with credential-providers to read credentials.

bash
npm install @aws-sdk/client-s3 @aws-sdk/client-sts @aws-sdk/client-servicediscovery @aws-sdk/credential-providers
npm pkg set type=module

I wrote the code in TypeScript and ran it directly with Node.js. Starting with Node.js 22.18.0, running .ts files with type annotations stripped is enabled by default (no type checking is done). To write import statements, I set "type": "module" in package.json.

Keep the emulator running, open another terminal, and set the environment variables described in the official documentation. The last line, NODE_EXTRA_CA_CERTS, is the one extra line needed for Node.js.

bash
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
export NODE_EXTRA_CA_CERTS=~/.aws/emulator/9297/ca.pem

The SDK for JavaScript v3 is one of the SDKs that support AWS_ENDPOINT_URL to set the endpoint. In my test, the endpoint, credentials, and region were all read from these environment variables. The diagram below summarizes which variables were read and which ones needed other settings.

In the SDK for JavaScript v3, the environment variables for the endpoint, credentials, and region were read. AWS_CA_BUNDLE was not read, so NODE_EXTRA_CA_CERTS is needed. AWS_DISABLE_HOST_PREFIX_INJECTION had no effect, so disableHostPrefix: true is needed. With localhost, the S3 bucket name is added to the hostname, so keep 127.0.0.1
Environment variables for the AWS CLI: which ones the SDK for JavaScript v3 read, and which ones needed other settings (the labels in the image are in Japanese)

The certificate is not read through AWS_CA_BUNDLE

First, I used GetCallerIdentity from STS to check where the request reached. The endpoint and credentials are not written in the code.

ts
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";

// Endpoint, credentials, and region are read from environment variables (not written in the code)
const sts = new STSClient({});
const me = await sts.send(new GetCallerIdentityCommand({}));
console.log("Arn:", me.Arn);

When I ran this before setting NODE_EXTRA_CA_CERTS, it stopped with a certificate error, even though AWS_CA_BUNDLE was set. (Stack traces are shortened, and the home directory path is replaced with ~.)

text
$ echo "AWS_CA_BUNDLE=$AWS_CA_BUNDLE"; node whoami.ts
AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
(省略)
Error: self-signed certificate
(省略)
  code: 'DEPTH_ZERO_SELF_SIGNED_CERT',

The official documentation says that AWS_CA_BUNDLE is what reads the certificate for the AWS CLI, Boto3, and the SDK for Go. For the SDK for JavaScript v3, it instructs you to set the path to ca.pem in NODE_EXTRA_CA_CERTS. After I set it and ran the code again, the request reached the emulator. The emulator's account ID is a fixed value made of twelve zeros (the output below shows it as a placeholder, <12桁の0>).

text
$ export NODE_EXTRA_CA_CERTS=~/.aws/emulator/9297/ca.pem
$ node whoami.ts
Arn: arn:aws:iam::<12桁の0>:user/emulator

According to the Node.js documentation, NODE_EXTRA_CA_CERTS adds ca.pem to the certificates Node.js already trusts, and the existing certificates still work. The variable is read only when the process starts, so setting it with process.env inside the code has no effect. The emulator regenerates its certificate on each start, but this setting points to the file path, so you do not need to change it each time.

Write and read an object in S3

For S3, you also just create the client with new S3Client({}). The code below creates a bucket, writes a string, then lists the objects and reads the contents.

ts
import {
  S3Client,
  CreateBucketCommand,
  PutObjectCommand,
  GetObjectCommand,
  ListObjectsV2Command,
} from "@aws-sdk/client-s3";

const s3 = new S3Client({});
const Bucket = "example-bucket";

await s3.send(new CreateBucketCommand({ Bucket }));
await s3.send(new PutObjectCommand({ Bucket, Key: "hello.txt", Body: "にゃー" }));

const list = await s3.send(new ListObjectsV2Command({ Bucket }));
console.log("Keys:", list.Contents?.map((o) => o.Key));

const obj = await s3.send(new GetObjectCommand({ Bucket, Key: "hello.txt" }));
console.log("hello.txt:", await obj.Body?.transformToString());
text
$ node s3.ts
Keys: [ 'hello.txt' ]
hello.txt: にゃー

With localhost as the endpoint, only S3 fails to connect

When I changed AWS_ENDPOINT_URL to https://localhost:9297 and ran the same code, it failed because the hostname example-bucket.localhost could not be found. The bucket name had been added in front of the hostname.

text
$ AWS_ENDPOINT_URL=https://localhost:9297 node s3.ts
(省略)
Error: getaddrinfo ENOTFOUND example-bucket.localhost

S3 supports two ways to address a bucket: putting the bucket name in the URL path (path-style), and putting it in the hostname (virtual-hosted style). According to the emulator's official documentation, if the endpoint is an IP address, the SDK sends path-style requests. But if the endpoint is localhost, the SDK for JavaScript uses the hostname style by default. The emulator does not accept the hostname form, so the documentation says to keep AWS_ENDPOINT_URL set to 127.0.0.1.

If you must use localhost, pass forcePathStyle: true to the S3 client. With that setting, requests are sent path-style, and they reached the emulator in my test. s3-path-style.ts is s3.ts with the client changed to this one line, and the bucket name changed to example-bucket-2. The certificate is also issued for the name localhost, so there is no certificate error.

ts
const s3 = new S3Client({ forcePathStyle: true });
text
$ AWS_ENDPOINT_URL=https://localhost:9297 node s3-path-style.ts
Keys: [ 'hello.txt' ]
hello.txt: にゃー
$ openssl x509 -in ~/.aws/emulator/9297/ca.pem -noout -ext subjectAltName
X509v3 Subject Alternative Name: 
    DNS:localhost, IP Address:127.0.0.1, IP Address:0:0:0:0:0:0:0:1

For APIs that add data- to the hostname, pass disableHostPrefix: true

Some APIs have the SDK add a prefix in front of the hostname. The official documentation gives examples such as data- for Cloud Map's DiscoverInstances and sync- for Step Functions' StartSyncExecution. The AWS CLI and Boto3 can turn this off with AWS_DISABLE_HOST_PREFIX_INJECTION. For the SDK for JavaScript v3, the documentation says to pass disableHostPrefix: true when you create the client.

I checked this with a script that creates a namespace and a service in Cloud Map, registers one instance, and then calls DiscoverInstances (the setup code is omitted). The script sets disableHostPrefix: true only when the argument on is passed.

ts
const disableHostPrefix = process.argv[2] === "on";
const sd = new ServiceDiscoveryClient({ disableHostPrefix });

Even in a shell where I set AWS_DISABLE_HOST_PREFIX_INJECTION=true, the request failed without disableHostPrefix, because it tried to reach data-127.0.0.1. With disableHostPrefix passed, the registered instance was returned.

text
$ echo "AWS_DISABLE_HOST_PREFIX_INJECTION=$AWS_DISABLE_HOST_PREFIX_INJECTION"; node discover.ts
AWS_DISABLE_HOST_PREFIX_INJECTION=true
disableHostPrefix: false -> Error getaddrinfo ENOTFOUND data-127.0.0.1
$ node discover.ts on
disableHostPrefix: true -> [ { AWS_INSTANCE_IPV4: '192.0.2.10' } ]

The official documentation notes that setting AWS_DISABLE_HOST_PREFIX_INJECTION makes these operations fail on real AWS, so it should be set only in the shell that uses the emulator.

If the access key environment variables remain, the emulator rejects the requests

According to the official documentation, environment variables such as AWS_ACCESS_KEY_ID take priority over the credentials file. If you leave them set without the unset above, the SDK signs requests with those values, and the emulator rejects them. When I ran the code with made-up values, the emulator returned InvalidClientTokenId (HTTP 403). (The output below is shortened to the key lines.)

text
$ AWS_ACCESS_KEY_ID=not-a-real-key AWS_SECRET_ACCESS_KEY=not-a-real-secret node whoami.ts
InvalidClientTokenId: The security token included in the request is invalid.
  '$fault': 'client',
  '$metadata': {
    httpStatusCode: 403,
(省略)

Specify the settings in code instead of environment variables

NODE_EXTRA_CA_CERTS has to be decided before the process starts. If you want the test to be self-contained in its code, you can pass the endpoint, region, credentials, and certificate directly to the client. An endpoint given in code takes priority over AWS_ENDPOINT_URL in the environment. Writing the httpsAgent settings directly in requestHandler is a shorter form available from SDK version 3.521.0.

ts
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3";
import { fromIni } from "@aws-sdk/credential-providers";

// Location of the files the emulator writes each time it starts (for port 9297)
const dir = join(homedir(), ".aws", "emulator", "9297");

const s3 = new S3Client({
  endpoint: "https://127.0.0.1:9297",
  region: "us-east-1",
  credentials: fromIni({ filepath: join(dir, "emulator_credentials") }),
  requestHandler: {
    httpsAgent: { ca: readFileSync(join(dir, "ca.pem")) },
  },
});

const out = await s3.send(new ListBucketsCommand({}));
console.log("Buckets:", out.Buckets?.map((b) => b.Name));

I ran this with env -i, which removes all environment variables except PATH and HOME. The request still reached the emulator, and the buckets I created earlier were listed.

text
$ env -i PATH="$PATH" HOME="$HOME" node explicit.ts
Buckets: [ 'example-bucket', 'example-bucket-2' ]

According to the Node.js documentation, when you pass ca, the certificates Node.js trusts by default are no longer used. This client can only connect to the emulator, so create it separately from any client for real AWS.

Use it from tests with node:test

I wrote a test that uses S3 with Node.js's built-in node:test. In before, the test first checks that the endpoint is the emulator.

ts
import { test, before } from "node:test";
import assert from "node:assert/strict";
import {
  S3Client,
  CreateBucketCommand,
  PutObjectCommand,
  GetObjectCommand,
} from "@aws-sdk/client-s3";

const s3 = new S3Client({});
const Bucket = "test-bucket";

before(async () => {
  // If the endpoint is not the emulator, fail here
  assert.equal(process.env.AWS_ENDPOINT_URL, "https://127.0.0.1:9297");
  await s3.send(new CreateBucketCommand({ Bucket }));
});

test("書いたオブジェクトを、そのまま読み出せる", async () => {
  await s3.send(new PutObjectCommand({ Bucket, Key: "a.json", Body: JSON.stringify({ n: 1 }) }));
  const obj = await s3.send(new GetObjectCommand({ Bucket, Key: "a.json" }));
  assert.deepEqual(JSON.parse(await obj.Body!.transformToString()), { n: 1 });
});

test("ないキーを読むと NoSuchKey になる", async () => {
  await assert.rejects(
    s3.send(new GetObjectCommand({ Bucket, Key: "missing.json" })),
    { name: "NoSuchKey" },
  );
});

When I ran this in a shell with the environment variables set, both tests passed (part of the output is omitted).

text
$ node --test s3.test.ts
ok 1 - 書いたオブジェクトを、そのまま読み出せる
ok 2 - ないキーを読むと NoSuchKey になる
1..2
# tests 2
# pass 2
# fail 0

When I ran it with AWS_ENDPOINT_URL unset, the assert.equal in before failed, and both tests failed. (Only the lines with AssertionError and related details are shown.)

text
$ env -u AWS_ENDPOINT_URL node --test s3.test.ts
not ok 1 - 書いたオブジェクトを、そのまま読み出せる
    + actual - expected
  name: 'AssertionError'
  expected: 'https://127.0.0.1:9297'
not ok 2 - ないキーを読むと NoSuchKey になる
    + actual - expected
  name: 'AssertionError'
  expected: 'https://127.0.0.1:9297'
# pass 0
# fail 2
Warning

According to the official documentation, if AWS_ENDPOINT_URL is not set in the shell that runs the tests, the code will use whatever credentials it finds to call real AWS. The documentation recommends setting the environment variables inside the script that runs the tests, and not putting real credentials in the test job's environment.

​Posted by 86