Skip to main content
The @aws-sdk/credential-providers package exports a set of factory functions that each return an AwsCredentialIdentityProvider — an async function that resolves AWS credentials from a specific source. Pass any provider directly to the credentials option of any SDK client.
npm install @aws-sdk/credential-providers

Using a provider with a client

import { S3Client } from "@aws-sdk/client-s3";
import { fromIni } from "@aws-sdk/credential-providers";

const client = new S3Client({
  region: "us-east-1",
  credentials: fromIni({ profile: "my-profile" }),
});
The client caches the resolved credentials and automatically refreshes them when fewer than 5 minutes remain before the expiration date.

Providers

Package: @aws-sdk/credential-providers
Environments: Node.js only
Reads static credentials from environment variables. Throws if AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY are missing or empty.Reads these variables:
VariableRequiredDescription
AWS_ACCESS_KEY_IDYesAccess key ID
AWS_SECRET_ACCESS_KEYYesSecret access key
AWS_SESSION_TOKENNoSession token for temporary credentials
AWS_CREDENTIAL_EXPIRATIONNoISO-8601 expiration timestamp
import { fromEnv } from "@aws-sdk/credential-providers";

const client = new FooClient({
  credentials: fromEnv(),
});
Package: @aws-sdk/credential-providers
Environments: Node.js only
Inner clients used: @aws-sdk/client-sso or @aws-sdk/client-sts (depending on profile configuration)
Reads credentials from ~/.aws/credentials and ~/.aws/config. Profiles in the credentials file take precedence over those in the config file. Supports role assumption, MFA, SSO, and web identity token profiles.
import { fromIni } from "@aws-sdk/credential-providers";

const client = new FooClient({
  // You can also set the profile at the client level (v3.714.0+).
  profile: "my-profile",
  region: "us-west-2",

  credentials: fromIni({
    // Optional. Defaults to the client's profile if set.
    profile: "my-profile",
    // Optional. Defaults to AWS_SHARED_CREDENTIALS_FILE or ~/.aws/credentials.
    filepath: "~/.aws/credentials",
    // Optional. Defaults to AWS_CONFIG_FILE or ~/.aws/config.
    configFilepath: "~/.aws/config",
    // Optional. Required when the profile uses MFA.
    mfaCodeProvider: async (mfaSerial) => {
      return "token";
    },
    // Optional. Overrides for the inner STS or SSO client.
    clientConfig: {},
  }),
});
Sample ~/.aws/credentials:
[default]
aws_access_key_id=foo
aws_secret_access_key=bar

[dev]
aws_access_key_id=foo2
aws_secret_access_key=bar2
Sample ~/.aws/config:
[default]
aws_access_key_id=foo
aws_secret_access_key=bar

[profile dev]
aws_access_key_id=foo2
aws_secret_access_key=bar2
Profile with role assumption:
[second]
aws_access_key_id=foo
aws_secret_access_key=bar

[first]
source_profile=second
role_arn=arn:aws:iam::123456789012:role/example-role-arn
Force reload from disk (bypass cache):
import { S3Client } from "@aws-sdk/client-s3";
import { fromIni } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromIni({ ignoreCache: true }),
});
Package: @aws-sdk/credential-providers
Environments: Node.js only
The same credential chain used automatically by Node.js SDK clients. Useful when you need a provider reference explicitly — for example, when constructing a presigner or RDS signer utility outside of a client.Tries the following sources in order, stopping at the first success:
  1. Environment variables (fromEnv)
  2. SSO token cache (fromSSO)
  3. Web identity token file (fromTokenFile)
  4. Shared INI files (fromIni)
  5. Container metadata (fromContainerMetadata)
  6. EC2 instance metadata (fromInstanceMetadata)
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

const credentialProvider = fromNodeProviderChain({
  // Accepts any option from the providers in the chain.
  // Optional overrides for the inner credentials client (STS, SSO, etc.).
  clientConfig: {},
});
Package: @aws-sdk/credential-providers
Environments: Node.js only
Inner clients used: @aws-sdk/client-sso, @aws-sdk/client-sso-oidc
Reads a cached SSO access token from disk (written by aws configure sso or aws sso login) and exchanges it for temporary AWS credentials.
fromSSO only works with profiles that use SSO credentials directly. If the profile assumes a role on top of SSO, use fromIni() instead.
Login flow:
$ aws configure sso
...
CLI profile name [123456789011_ReadOnly]: my-sso-profile
import { fromSSO } from "@aws-sdk/credential-providers";

const client = new FooClient({
  profile: "my-sso-profile",
  credentials: fromSSO({
    // Optional. Defaults to the client's profile if set.
    profile: "my-sso-profile",
    // Optional. Provide inline SSO parameters instead of reading from a profile.
    ssoStartUrl: "https://d-abc123.awsapps.com/start",
    ssoAccountId: "1234567890",
    ssoRegion: "us-east-1",
    ssoRoleName: "SampleRole",
    // Optional. Overrides for the inner SSO client.
    clientConfig: { region: "us-east-1" },
  }),
});
Sample ~/.aws/config:
[profile sample-profile]
sso_account_id = 012345678901
sso_region = us-east-1
sso_role_name = SampleRole
sso_start_url = https://d-abc123.awsapps.com/start
To log out:
$ aws sso logout
Successfully signed out of all SSO profiles.
Package: @aws-sdk/credential-providers
Environments: Node.js, browsers, native apps
Inner clients used: @aws-sdk/client-sts
Calls STS AssumeRole to obtain short-lived credentials for the specified role. Supports chaining role assumptions and MFA.
import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

const client = new FooClient({
  region,
  credentials: fromTemporaryCredentials({
    // Optional. Source credentials used to call AssumeRole.
    // If omitted, uses the default credential chain.
    masterCredentials: fromTemporaryCredentials({
      params: { RoleArn: "arn:aws:iam::1234567890:role/RoleA" },
    }),
    // Required. Parameters passed to STS AssumeRole.
    params: {
      RoleArn: "arn:aws:iam::1234567890:role/RoleB",
      // Optional. Defaults to a generated name with prefix 'aws-sdk-js-'.
      RoleSessionName: "aws-sdk-js-123",
      // Optional. Session duration in seconds.
      DurationSeconds: 3600,
    },
    // Optional. Required when the role requires MFA.
    mfaCodeProvider: async (mfaSerial) => {
      return "token";
    },
    // Optional. Overrides for the inner STS client.
    clientConfig: {},
  }),
});
Package: @aws-sdk/credential-providers
Environments: Node.js, browsers, native apps
Inner clients used: @aws-sdk/client-sts
Exchanges an OAuth 2.0 or OpenID Connect token for temporary AWS credentials by calling STS AssumeRoleWithWebIdentity. Supported identity providers include Login with Amazon, Facebook Login, and Google Sign-In.
import { fromWebToken } from "@aws-sdk/credential-providers";

const client = new FooClient({
  region,
  credentials: fromWebToken({
    // Required. The role to assume.
    roleArn: "arn:aws:iam::1234567890:role/RoleA",
    // Required. The OIDC/OAuth token from the identity provider.
    webIdentityToken: await openIdProvider(),
    // Optional. Session name for the assumed role.
    roleSessionName: "session_123",
    // Optional. Host of the identity provider (e.g. "graph.facebook.com").
    providerId: "graph.facebook.com",
    // Optional. Managed session policies.
    policyArns: [{ arn: "arn:aws:iam::1234567890:policy/SomePolicy" }],
    // Optional. Inline session policy in JSON format.
    policy: "JSON_STRING",
    // Optional. Session duration in seconds. Default: 3600.
    durationSeconds: 7200,
    // Optional. Overrides for the inner STS client.
    clientConfig: {},
  }),
});
For Kubernetes and other environments where the token is written to a file, use fromTokenFile() instead.
Package: @aws-sdk/credential-providers
Environments: Node.js only
Inner clients used: @aws-sdk/client-sts
Reads an OIDC token from a file on disk and calls STS AssumeRoleWithWebIdentity. Configuration can come from options or environment variables.
OptionEnvironment variableRequiredDescription
webIdentityTokenFileAWS_WEB_IDENTITY_TOKEN_FILEYesPath to the token file
roleArnAWS_ROLE_ARNYesRole to assume
roleSessionNameAWS_ROLE_SESSION_NAMENoSession name
import { fromTokenFile } from "@aws-sdk/credential-providers";

const client = new FooClient({
  region: "us-west-2",
  credentials: fromTokenFile({
    // Optional. Overrides for the inner STS client.
    clientConfig: {},
  }),
});
Package: @aws-sdk/credential-providers
Environments: Node.js only
Retrieves credentials for the IAM role associated with the current ECS task from the container metadata service. Requires the task to have an IAM role configured.
import { fromContainerMetadata } from "@aws-sdk/credential-providers";

const client = new FooClient({
  credentials: fromContainerMetadata({
    // Optional. Connection timeout in milliseconds. Default: 1000.
    timeout: 1000,
    // Optional. Max HTTP retries. Default: 0.
    maxRetries: 0,
  }),
});
Package: @aws-sdk/credential-providers
Environments: Node.js only
Retrieves credentials for the IAM role attached to the current EC2 instance from the instance metadata service. Both IMDSv1 and IMDSv2 are supported.
import { fromInstanceMetadata } from "@aws-sdk/credential-providers";

const client = new FooClient({
  credentials: fromInstanceMetadata({
    // Optional. Connection timeout in milliseconds. Default: 1000.
    timeout: 1000,
    // Optional. Max HTTP retries. Default: 0.
    maxRetries: 0,
  }),
});
Package: @aws-sdk/credential-providers
Environments: Node.js, browsers, native apps
Inner clients used: @aws-sdk/client-cognito-identity
Retrieves AWS credentials for a known Cognito Identity ID by calling the GetCredentialsForIdentity API. Use when you already have an identity ID.
import { fromCognitoIdentity } from "@aws-sdk/credential-providers";

const client = new FooClient({
  region,
  credentials: fromCognitoIdentity({
    // Required. The Cognito identity ID.
    identityId: "us-east-1:128d0a74-c82f-4553-916d-90053example",
    // Optional. Role ARN when multiple roles are available.
    customRoleArn: "arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity",
    // Optional. Required for external identity providers (Facebook, Google, etc.).
    logins: {
      "graph.facebook.com": "FBTOKEN",
      "accounts.google.com": "GOOGLETOKEN",
    },
    // Optional. Overrides for the inner Cognito client.
    clientConfig: {},
  }),
});
Package: @aws-sdk/credential-providers
Environments: Node.js, browsers, native apps
Inner clients used: @aws-sdk/client-cognito-identity
Calls GetId to obtain a Cognito identity ID from an identity pool, then calls GetCredentialsForIdentity to retrieve credentials. The identity ID is cached internally; credentials are not.
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";

const client = new FooClient({
  region,
  credentials: fromCognitoIdentityPool({
    // Required. The identity pool ID.
    identityPoolId: "us-east-1:1699ebc0-7900-4099-b910-2df94f52a030",
    // Optional. AWS account ID.
    accountId: "123456789",
    // Optional. Storage for caching resolved identity IDs.
    cache: custom_storage,
    // Optional. Per-user cache key.
    userIdentifier: "user_0",
    // Optional. Role ARN when multiple roles are available.
    customRoleArn: "arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity",
    // Optional. Required for external identity providers.
    logins: {
      "graph.facebook.com": "FBTOKEN",
      "accounts.google.com": "GOOGLETOKEN",
    },
    // Optional. Overrides for the inner Cognito client.
    clientConfig: {},
  }),
});
Package: @aws-sdk/credential-providers
Environments: Node.js, browsers (HTTPS only in browsers)
Makes an HTTP(S) GET request to a credential-serving endpoint and parses JSON credentials from the response. A general form of fromContainerMetadata. Accepts HTTPS URLs or a limited set of HTTP endpoints (loopback, ECS/EKS metadata hosts).
import { fromHttp } from "@aws-sdk/credential-providers";

const client = new FooClient({
  credentials: fromHttp({
    // Provide one of:
    awsContainerCredentialsFullUri: "https://my-credential-server.example.com/credentials",
    // or
    awsContainerCredentialsRelativeUri: "/credentials", // appended to 169.254.170.2

    // Optional authorization token:
    awsContainerAuthorizationToken: "my-token",
    // or read token from file:
    awsContainerAuthorizationTokenFile: "/path/to/token",
  }),
});
Environment variables are also accepted if options are not provided in code:
VariableDescription
AWS_CONTAINER_CREDENTIALS_FULL_URIFull URI to the credential endpoint
AWS_CONTAINER_CREDENTIALS_RELATIVE_URIPath appended to 169.254.170.2
AWS_CONTAINER_AUTHORIZATION_TOKENAuthorization token value
AWS_CONTAINER_AUTHORIZATION_TOKEN_FILEPath to file containing the token
Package: @aws-sdk/credential-providers
Environments: Node.js only
Inner clients used: @aws-sdk/client-signin
Reads cached credentials stored on disk after running aws login. Useful when users authenticate via the AWS Management Console experience. Part of fromNodeProviderChain.
import { fromLoginCredentials } from "@aws-sdk/credential-providers";

const client = new FooClient({
  profile: "my-profile",
  credentials: fromLoginCredentials({
    profile: "my-profile",
    clientConfig: { region: "us-east-1" },
  }),
});
$ aws login
$ aws login --profile my-dev-profile
Package: @aws-sdk/credential-providers
Environments: Node.js, browsers, native apps
Composes multiple provider functions into a single provider. The chain tries each provider in order and returns the first successful result. You can mix built-in providers with your own async functions.
import { fromEnv, fromIni, createCredentialChain } from "@aws-sdk/credential-providers";
import { S3 } from "@aws-sdk/client-s3";

// Mix built-in providers with a custom async function.
new S3({
  credentials: createCredentialChain(
    fromEnv(),
    async () => {
      // credentials from any custom source
      return credentials;
    },
    fromIni()
  ),
});
Force credential refresh with expireAfter:Use .expireAfter(milliseconds) to set a client-side expiry on credentials that don’t include one. This causes the chain to be re-evaluated before the expiry window closes (5 minutes before expiry).
import { fromEnv, fromIni, createCredentialChain } from "@aws-sdk/credential-providers";
import { S3 } from "@aws-sdk/client-s3";

// Credentials expire after 15 minutes client-side.
// The provider is called roughly every 10 minutes under continuous use.
new S3({
  credentials: createCredentialChain(fromEnv(), fromIni()).expireAfter(15 * 60_000),
});
Shared init options across providers:
const init = { logger: console };

new S3({
  credentials: createCredentialChain(fromEnv(init), fromIni(init)),
});

Region resolution in credential providers

When a credential provider uses an inner client (STS, SSO, Cognito), the region for that inner client is resolved in this priority order:
  1. clientConfig.region passed directly to the credential provider
  2. The region field in the active profile (when resolving from config file)
  3. The outer SDK client’s region
  4. AWS_REGION environment variable
  5. us-east-1 fallback (legacy)
To keep behavior predictable, pass a consistent region to both the outer client and the credential provider’s clientConfig:
import { fromCognitoIdentity } from "@aws-sdk/credential-providers";

new S3Client({
  region: "us-west-2",
  credentials: fromCognitoIdentity({
    clientConfig: {
      region: "us-west-2",
    },
  }),
});

Build docs developers (and LLMs) love