Skip to main content
@aws-sdk/credential-providers is a collection of factory functions that each return an AwsCredentialIdentityProvider. Pass the result to any SDK client’s credentials option.
npm install @aws-sdk/credential-providers

AwsCredentialIdentityProvider type

Every function in this package returns the same type:
type AwsCredentialIdentityProvider = () => Promise<{
  accessKeyId: string;
  secretAccessKey: string;
  sessionToken?: string;
  expiration?: Date;
}>;
The SDK client caches the resolved credentials until less than 5 minutes remain before expiration, at which point it calls the provider again.

fromEnv()

Reads credentials from environment variables. Not available in browsers.
import { fromEnv } from "@aws-sdk/credential-providers";

const client = new S3Client({ credentials: fromEnv() });
Environment variables read:
VariableRequiredDescription
AWS_ACCESS_KEY_IDYesAWS access key
AWS_SECRET_ACCESS_KEYYesAWS secret key
AWS_SESSION_TOKENNoSession token for temporary credentials
AWS_CREDENTIAL_EXPIRATIONNoISO-8601 expiration timestamp
Rejects if AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY is missing.

fromIni(options?)

Reads from ~/.aws/credentials and ~/.aws/config. May use @aws-sdk/client-sts or @aws-sdk/client-sso internally. Not available in browsers.
import { fromIni } from "@aws-sdk/credential-providers";

const client = new S3Client({
  profile: "my-profile",
  credentials: fromIni({
    profile: "my-profile",
    filepath: "~/.aws/credentials",
    configFilepath: "~/.aws/config",
    mfaCodeProvider: async (mfaSerial) => "123456",
    clientConfig: {},
  }),
});
options.profile
string
Profile to read from the credentials/config file. Defaults to the value of AWS_PROFILE, then default. If the parent client has profile set, that value is inherited unless overridden here.
options.filepath
string
default:"~/.aws/credentials"
Path to the shared credentials file. Falls back to AWS_SHARED_CREDENTIALS_FILE environment variable.
options.configFilepath
string
default:"~/.aws/config"
Path to the shared config file. Falls back to AWS_CONFIG_FILE environment variable.
options.mfaCodeProvider
(mfaSerial: string) => Promise<string>
Required when the selected profile uses MFA (mfa_serial). Called with the MFA serial ARN; must return the one-time token.
options.ignoreCache
boolean
default:"false"
When true, always reloads credentials from the filesystem instead of using cached values. Useful for detecting credential file changes at runtime.
options.clientConfig
object
Configuration overrides passed to any inner STS or SSO client instantiated during credential resolution.
Sample credentials file:
[default]
aws_access_key_id=AKIAIOSFODNN7EXAMPLE
aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

[dev]
aws_access_key_id=AKIAI44QH8DHBEXAMPLE
aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

fromNodeProviderChain(options?)

The default credential chain used by Node.js SDK clients. Useful for utility functions (presigners, RDS signer) that need credentials outside a client context. Not available in browsers. Attempts each source in order, stopping at the first that succeeds:
  1. Environment variables (fromEnv)
  2. SSO token cache (fromSSO)
  3. Web identity token file (fromTokenFile)
  4. Shared INI files (fromIni)
  5. EC2/ECS instance metadata (fromContainerMetadata, fromInstanceMetadata)
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

const credentials = fromNodeProviderChain({
  clientConfig: { region: "us-east-1" },
});
options.clientConfig
object
Passed to any inner credentials client (STS, SSO, etc.) instantiated during the chain.
You do not need to call fromNodeProviderChain explicitly when constructing an SDK client — it is the default. Use it when you need a credential provider reference for something like getSignedUrl.

fromSSO(options)

Reads cached SSO access tokens from disk and exchanges them for temporary AWS credentials. Uses @aws-sdk/client-sso and @aws-sdk/client-sso-oidc. Not available in browsers.
This provider only works for profiles that use SSO credentials directly. For profiles that assume a role on top of SSO, use fromIni instead.
import { fromSSO } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromSSO({
    ssoStartUrl: "https://d-abc123.awsapps.com/start",
    ssoAccountId: "123456789012",
    ssoRegion: "us-east-1",
    ssoRoleName: "SampleRole",
  }),
});
You can also load SSO config from the shared config file by specifying a profile:
const client = new S3Client({
  credentials: fromSSO({ profile: "my-sso-profile" }),
});
options.profile
string
Profile name in ~/.aws/config or ~/.aws/credentials. Required when not passing inline sso* parameters.
options.ssoStartUrl
string
The URL to the AWS SSO portal (e.g., https://d-abc123.awsapps.com/start). Required if using inline SSO params.
options.ssoAccountId
string
AWS account ID for the SSO session. Required if using inline SSO params.
options.ssoRegion
string
AWS region where the SSO service is hosted. Required if using inline SSO params.
options.ssoRoleName
string
Name of the IAM role to assume via SSO. Required if using inline SSO params.
options.ssoSession
string
Named SSO session as configured in ~/.aws/config with [sso-session] sections.
options.filepath
string
default:"~/.aws/credentials"
Path to the shared credentials file.
options.configFilepath
string
default:"~/.aws/config"
Path to the shared config file.
options.clientConfig
object
Configuration overrides for the inner SSO client.
SSO login with AWS CLI:
# 1. Configure an SSO profile
aws configure sso
# Follow prompts, name your profile "my-sso-profile"

# 2. Log in
aws sso login --profile my-sso-profile

# 3. Log out
aws sso logout

fromTemporaryCredentials(options)

Assumes an IAM role via STS AssumeRole and returns temporary credentials. Uses @aws-sdk/client-sts. Available in browsers and native apps.
import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/MyRole",
      RoleSessionName: "my-session",
      DurationSeconds: 3600,
    },
    clientConfig: { region: "us-east-1" },
  }),
});
Role chaining example:
// Assume RoleA first, then use those credentials to assume RoleB
const client = new S3Client({
  credentials: fromTemporaryCredentials({
    masterCredentials: fromTemporaryCredentials({
      params: { RoleArn: "arn:aws:iam::123456789012:role/RoleA" },
    }),
    params: { RoleArn: "arn:aws:iam::123456789012:role/RoleB" },
  }),
});
options.params
AssumeRoleCommandInput
required
Parameters passed directly to the STS AssumeRole API. Must include RoleArn. RoleSessionName defaults to a random value prefixed with aws-sdk-js-.
options.params.RoleArn
string
required
ARN of the role to assume.
options.params.RoleSessionName
string
Identifier for the assumed role session. Auto-generated if omitted.
options.params.DurationSeconds
number
Duration of the role session in seconds.
options.masterCredentials
AwsCredentialIdentityProvider
Credentials used to call STS. Defaults to the standard credential chain if omitted.
options.mfaCodeProvider
(mfaSerial: string) => Promise<string>
Required when params.SerialNumber is set. Must return the MFA token.
options.clientConfig
object
Configuration overrides for the inner STS client.

fromWebToken(options)

Calls STS AssumeRoleWithWebIdentity using an OIDC/OAuth2 token. Uses @aws-sdk/client-sts. Available in browsers and native apps.
import { fromWebToken } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromWebToken({
    roleArn: "arn:aws:iam::123456789012:role/MyFederatedRole",
    webIdentityToken: await getTokenFromIdP(),
    roleSessionName: "web-session",
    durationSeconds: 7200,
  }),
});
options.roleArn
string
required
ARN of the role to assume.
options.webIdentityToken
string
required
The OAuth 2.0 access token or OpenID Connect ID token from the identity provider.
options.roleSessionName
string
Identifier for the assumed role session.
options.providerId
string
The fully qualified domain name of the identity provider (e.g., graph.facebook.com).
options.policyArns
object[]
ARNs of IAM managed policies to use as managed session policies.
options.policy
string
An inline session policy in JSON format.
options.durationSeconds
number
default:"3600"
Duration of the role session in seconds.
options.clientConfig
object
Configuration overrides for the inner STS client.

fromTokenFile(options?)

Reads an OIDC token from a file path and calls STS AssumeRoleWithWebIdentity. Configuration is typically provided via environment variables in Kubernetes/EKS environments. Uses @aws-sdk/client-sts. Not available in browsers.
import { fromTokenFile } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromTokenFile({ clientConfig: { region: "us-east-1" } }),
});
OptionEnvironment variableRequiredDescription
webIdentityTokenFileAWS_WEB_IDENTITY_TOKEN_FILEYesPath to the OIDC token file
roleArnAWS_ROLE_ARNYesIAM role ARN to assume
roleSessionNameAWS_ROLE_SESSION_NAMENoSession name
options.clientConfig
object
Configuration overrides for the inner STS client.

fromContainerMetadata(options?)

Reads credentials from the ECS container metadata service. Returns credentials for the IAM role associated with the ECS task. Not available in browsers.
import { fromContainerMetadata } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromContainerMetadata({
    timeout: 1000,
    maxRetries: 0,
  }),
});
options.timeout
number
default:"1000"
Connection timeout in milliseconds for requests to the metadata service.
options.maxRetries
number
default:"0"
Maximum number of times to retry failed HTTP connections to the metadata service.

fromInstanceMetadata(options?)

Reads credentials from the EC2 Instance Metadata Service (IMDS). Supports both IMDSv1 and IMDSv2. Not available in browsers.
import { fromInstanceMetadata } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromInstanceMetadata({
    timeout: 1000,
    maxRetries: 0,
  }),
});
options.timeout
number
default:"1000"
Connection timeout in milliseconds.
options.maxRetries
number
default:"0"
Maximum number of HTTP connection retries.

fromHttp(options)

Makes a GET request to an HTTP(S) endpoint to retrieve credentials. This is a general form of fromContainerMetadata. Available in browsers (HTTPS only) and Node.js. The server must respond with:
type HttpProviderResponse = {
  AccessKeyId: string;
  SecretAccessKey: string;
  Token: string;
  AccountId?: string;
  Expiration: string; // RFC 3339
};
import { fromHttp } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromHttp({
    awsContainerCredentialsFullUri: "https://my-credential-server/credentials",
    awsContainerAuthorizationToken: "my-token",
  }),
});
Node.js options:
options.awsContainerCredentialsFullUri
string
Full URI to request credentials from. Mutually exclusive with awsContainerCredentialsRelativeUri. Falls back to AWS_CONTAINER_CREDENTIALS_FULL_URI.
options.awsContainerCredentialsRelativeUri
string
Relative URI appended to the link-local host 169.254.170.2. Falls back to AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.
options.awsContainerAuthorizationToken
string
Value for the Authorization request header. Falls back to AWS_CONTAINER_AUTHORIZATION_TOKEN.
options.awsContainerAuthorizationTokenFile
string
Path to a file containing the authorization token. Falls back to AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE.
The acceptable non-HTTPS destinations in Node.js are loopback addresses (127.0.0.0/8, [::1/128]), ECS container host (169.254.170.2), and EKS container host (169.254.170.23, [fd00:ec2::23]).

fromCognitoIdentity(options)

Retrieves credentials for a specific Cognito identity ID using the GetCredentialsForIdentity API. Uses @aws-sdk/client-cognito-identity. Available in browsers and native apps.
import { fromCognitoIdentity } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromCognitoIdentity({
    identityId: "us-east-1:128d0a74-c82f-4553-916d-90053example",
    logins: {
      "accounts.google.com": googleIdToken,
    },
    customRoleArn: "arn:aws:iam::123456789012:role/MyCognitoRole",
  }),
});
options.identityId
string
required
The unique Cognito identity ID against which credentials will be issued.
options.logins
Record<string, string>
Map of identity provider names to tokens. Required when using external identity providers (Facebook, Google, Amazon, Twitter).
options.customRoleArn
string
ARN of the role to assume when multiple roles were received from the identity provider token.
options.clientConfig
object
Configuration overrides for the inner Cognito Identity client.

fromCognitoIdentityPool(options)

Calls GetId to obtain a Cognito identity ID, then calls GetCredentialsForIdentity to get temporary credentials. The identity ID is cached internally. Uses @aws-sdk/client-cognito-identity. Available in browsers and native apps.
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromCognitoIdentityPool({
    identityPoolId: "us-east-1:1699ebc0-7900-4099-b910-2df94f52a030",
    logins: {
      "accounts.google.com": googleIdToken,
    },
    clientConfig: { region: "us-east-1" },
  }),
});
options.identityPoolId
string
required
The Cognito identity pool ID from which to retrieve or generate an identity.
options.logins
Record<string, string>
Map of identity provider names to tokens.
options.accountId
string
Standard AWS account ID (9+ digits).
options.customRoleArn
string
ARN of the role to assume when multiple roles are available.
options.cache
object
Custom storage object for caching resolved Cognito identity IDs.
options.userIdentifier
string
A unique identifier for the user, used as a cache key for identity IDs.
options.clientConfig
object
Configuration overrides for the inner Cognito Identity client.

fromProcess(options?)

Runs a process defined in the credential_process field of the AWS config/credentials file and reads JSON credentials from its standard output. Not available in browsers.
import { fromProcess } from "@aws-sdk/credential-providers";

const client = new S3Client({
  credentials: fromProcess({ profile: "my-profile" }),
});
options.profile
string
Profile to read from. Inherits from the parent client’s profile if set.
options.filepath
string
default:"~/.aws/credentials"
Path to the shared credentials file.
options.configFilepath
string
default:"~/.aws/config"
Path to the shared config file.
Sample credentials file:
[default]
credential_process = /usr/local/bin/awscreds

[profile dev]
credential_process = /usr/local/bin/awscreds dev

createCredentialChain(...providers)

Composes multiple credential providers into a single provider that tries each in order, resolving with the first one that succeeds.
import { fromEnv, fromIni, createCredentialChain } from "@aws-sdk/credential-providers";
import { S3Client } from "@aws-sdk/client-s3";

const client = new S3Client({
  credentials: createCredentialChain(
    fromEnv(),
    fromIni({ profile: "fallback-profile" }),
    async () => ({
      accessKeyId: "custom-key",
      secretAccessKey: "custom-secret",
    })
  ),
});
Force credential refresh with expireAfter:
// Credentials will be refreshed approximately every 10 minutes
// (15-minute window minus the 5-minute pre-expiry buffer)
const client = new S3Client({
  credentials: createCredentialChain(fromEnv(), fromIni()).expireAfter(15 * 60_000),
});
providers
AwsCredentialIdentityProvider[]
required
One or more credential providers to try in order. Custom async functions returning AwsCredentialIdentity are also accepted.
.expireAfter(milliseconds) — Chainable method that sets a client-side TTL on the returned credentials. When the expiration approaches within 5 minutes, the chain is invoked again. If omitted and no provider sets an expiration, the chain is only called once per client.

Region resolution in credential providers

When a credential provider uses an inner client (e.g., STS for fromTemporaryCredentials), the region for that inner client follows this priority order:
  1. clientConfig.region — passed directly to the credential provider
  2. Profile region — from the config file for the active profile (when resolving from config)
  3. Parent client region — the region of the SDK client using these credentials
  4. AWS_REGION environment variable
  5. Profile region — lower priority when not resolving from config
  6. us-east-1 — legacy fallback
Pass clientConfig: { region: "us-east-1" } to any provider that accepts it to ensure consistent STS/SSO request routing.

fromLoginCredentials(options?)

Reads cached credentials stored on disk after authenticating with the AWS CLI’s aws login command. Not available in browsers. Uses @aws-sdk/client-signin internally. This provider is typically used automatically via fromNodeProviderChain. Use it explicitly only if you need to control which profile to load.
import { fromLoginCredentials } from "@aws-sdk/credential-providers";

const client = new FooClient({
  profile: "my-profile",
  credentials: fromLoginCredentials({
    // Optional. Defaults to the client's profile if set.
    // Should match the profile used with 'aws login --profile <name>'.
    profile: "my-profile",
    // Optional. Override the region for the inner signin client.
    clientConfig: { region: "us-east-1" },
  }),
});
Login flow:
$ aws login
# or for a named profile:
$ aws login --profile my-dev-profile
options.profile
string
Profile name to load. Defaults to the parent client’s profile field, then default.
options.clientConfig
object
Configuration overrides for the inner signin client. Setting region here overrides the profile region.

Build docs developers (and LLMs) love