AWS credential provider that sources credentials from a Node.js environment using a prioritized chain of credential sources. It automatically attempts to find credentials from environment variables, SSO token cache, web identity tokens, shared credentials/config files, and EC2/ECS Instance Metadata Service in order of precedence.
npm install @aws-sdk/credential-provider-nodeimport {
defaultProvider,
DefaultProviderInit,
remoteProvider,
credentialsWillNeedRefresh,
credentialsTreatedAsExpired
} from "@aws-sdk/credential-provider-node";For CommonJS:
const {
defaultProvider,
DefaultProviderInit,
remoteProvider,
credentialsWillNeedRefresh,
credentialsTreatedAsExpired
} = require("@aws-sdk/credential-provider-node");import { defaultProvider } from "@aws-sdk/credential-provider-node";
import { S3Client } from "@aws-sdk/client-s3";
// Simple usage with default settings
const credentialProvider = defaultProvider();
const s3Client = new S3Client({ credentials: credentialProvider });
// Advanced usage with configuration
const credentialProvider = defaultProvider({
profile: "myprofile",
timeout: 5000,
maxRetries: 3,
logger: console
});The credential provider implements a chain-of-responsibility pattern where providers are invoked sequentially until valid credentials are found:
AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (skipped if profile is set)~/.aws/credentials and ~/.aws/config filesKey Features:
tryNextLink support for recoverable failuresCreates a memoized credential provider that attempts to find credentials from multiple sources in order of precedence.
/**
* Creates a credential provider that will attempt to find credentials from the
* following sources (listed in order of precedence):
* * Environment variables exposed via `process.env`
* * SSO credentials from token cache
* * Web identity token credentials
* * Shared credentials and config ini files
* * The EC2/ECS Instance Metadata Service
*/
function defaultProvider(init?: DefaultProviderInit): MemoizedProvider<AwsCredentialIdentity>;
/**
* Configuration options for the default credential provider.
* This is an intersection type that combines options from multiple credential provider interfaces.
*/
type DefaultProviderInit = FromIniInit &
FromHttpOptions &
RemoteProviderInit &
FromProcessInit &
(FromSSOInit & Partial<SsoCredentialsParameters>) &
FromTokenFileInit;
interface MemoizedProvider<T> {
(): Promise<T>;
/**
* Expiry time of the credentials returned by the provider.
*/
expireTime?: Date;
}
interface AwsCredentialIdentity {
/**
* AWS access key ID
*/
readonly accessKeyId: string;
/**
* AWS secret access key
*/
readonly secretAccessKey: string;
/**
* A security token that was issued by the AWS Security Token Service (STS).
* This is only required when using temporary credentials.
*/
readonly sessionToken?: string;
/**
* A Date when the identity or credential will no longer be accepted.
*/
readonly expiration?: Date;
}The configuration type for the default credential provider is also exported for use in custom implementations.
/**
* Configuration options type for the default credential provider.
* This is an intersection of multiple credential provider configuration interfaces.
*/
type DefaultProviderInit = FromIniInit &
FromHttpOptions &
RemoteProviderInit &
FromProcessInit &
(FromSSOInit & Partial<SsoCredentialsParameters>) &
FromTokenFileInit;Usage Examples:
import { defaultProvider, DefaultProviderInit } from "@aws-sdk/credential-provider-node";
import { getDefaultRoleAssumerWithWebIdentity } from "@aws-sdk/client-sts";
// Basic usage
const provider = defaultProvider();
const credentials = await provider();
// With profile configuration
const provider = defaultProvider({
profile: "production",
timeout: 10000
});
// For EKS IAM Roles for Service Accounts
const provider = defaultProvider({
roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity({
region: "us-east-1"
})
});
// With custom role assumption
const provider = defaultProvider({
roleAssumer: async (sourceCredentials, params) => {
// Custom role assumption logic
return assumeRoleWithCustomLogic(sourceCredentials, params);
},
mfaCodeProvider: async (serial) => {
// Custom MFA token provider
return await promptUserForMFA(serial);
}
});Configuration type for the default credential provider, combining options from multiple provider interfaces.
/**
* Configuration options type for the default credential provider.
* This is an intersection of multiple credential provider configuration interfaces.
*/
type DefaultProviderInit = FromIniInit &
FromHttpOptions &
RemoteProviderInit &
FromProcessInit &
(FromSSOInit & Partial<SsoCredentialsParameters>) &
FromTokenFileInit;Key Configuration Properties (from constituent interfaces):
profile?: string - Configuration profile namefilepath?: string - Path to shared credentials fileconfigFilepath?: string - Path to shared config fileroleAssumer?: (sourceCredentials: AwsCredentialIdentity, params: AssumeRoleParams) => Promise<AwsCredentialIdentity> - Function for assuming IAM rolesroleAssumerWithWebIdentity?: (params: AssumeRoleWithWebIdentityParams) => Promise<AwsCredentialIdentity> - Function for web identity role assumptionroleArn?: string - ARN of role to assumewebIdentityTokenFile?: string - Path to web identity token filessoStartUrl?: string - SSO start URL (optional)ssoAccountId?: string - SSO account ID (optional)ssoRegion?: string - SSO region (optional)ssoRoleName?: string - SSO role name (optional)ssoSession?: string - SSO session name (optional)mfaCodeProvider?: (mfaSerial: string) => Promise<string> - MFA token provider functiontimeout?: number - Connection timeout for remote requestsmaxRetries?: number - Maximum retry attempts for HTTP connectionslogger?: Logger - Logger instance for debuggingparentClientConfig?: { region?: string | Provider<string>; profile?: string; [key: string]: unknown } - Parent client configurationInternal function that provides credentials from remote sources like EC2/ECS Instance Metadata Service or ECS Container Metadata.
/**
* @internal
* Creates a credential provider for remote sources (EC2/ECS metadata)
*/
function remoteProvider(init: RemoteProviderInit | FromHttpOptions): Promise<AwsCredentialIdentityProvider>;
interface AwsCredentialIdentityProvider {
(): Promise<AwsCredentialIdentity>;
}This function:
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, AWS_CONTAINER_CREDENTIALS_FULL_URI)AWS_EC2_METADATA_DISABLED environment variable to disable IMDS accessInternal utility functions for determining when credentials need to be refreshed.
/**
* @internal
* Returns true if credentials have an expiration date.
*/
function credentialsWillNeedRefresh(credentials: AwsCredentialIdentity): boolean;
/**
* @internal
* Returns true if credentials expire within 5 minutes (300000ms).
*/
function credentialsTreatedAsExpired(credentials: AwsCredentialIdentity): boolean;These functions are used internally by the memoization logic to determine when cached credentials should be refreshed.
Internal constants for environment variable names used by the remote provider.
/**
* @internal
* Environment variable name for disabling EC2 Instance Metadata Service
*/
const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";This constant is used internally to check if IMDS access should be disabled.
interface MemoizedProvider<T> {
(): Promise<T>;
/**
* Expiry time of the credentials returned by the provider.
*/
expireTime?: Date;
}
interface AwsCredentialIdentity {
/**
* AWS access key ID
*/
readonly accessKeyId: string;
/**
* AWS secret access key
*/
readonly secretAccessKey: string;
/**
* A security token that was issued by the AWS Security Token Service (STS).
* This is only required when using temporary credentials.
*/
readonly sessionToken?: string;
/**
* A Date when the identity or credential will no longer be accepted.
*/
readonly expiration?: Date;
}
interface Logger {
debug(...content: any[]): void;
info(...content: any[]): void;
warn(...content: any[]): void;
error(...content: any[]): void;
}
/**
* Configuration options from @aws-sdk/credential-provider-ini
*/
interface FromIniInit {
profile?: string;
filepath?: string;
configFilepath?: string;
roleAssumer?: (sourceCredentials: AwsCredentialIdentity, params: AssumeRoleParams) => Promise<AwsCredentialIdentity>;
roleAssumerWithWebIdentity?: (params: AssumeRoleWithWebIdentityParams) => Promise<AwsCredentialIdentity>;
mfaCodeProvider?: (mfaSerial: string) => Promise<string>;
parentClientConfig?: { region?: string | Provider<string>; profile?: string; [key: string]: unknown };
}
/**
* Configuration options from @aws-sdk/credential-provider-http
*/
interface FromHttpOptions {
authorizationToken?: string;
credentialsFullUri?: string;
}
/**
* Configuration options from @smithy/credential-provider-imds
*/
interface RemoteProviderInit {
timeout?: number;
maxRetries?: number;
logger?: Logger;
}
/**
* Configuration options from @aws-sdk/credential-provider-process
*/
interface FromProcessInit {
profile?: string;
filepath?: string;
configFilepath?: string;
logger?: Logger;
}
/**
* Configuration options from @aws-sdk/credential-provider-sso
*/
interface FromSSOInit {
ssoStartUrl?: string;
ssoAccountId?: string;
ssoRegion?: string;
ssoRoleName?: string;
ssoSession?: string;
logger?: Logger;
}
/**
* Additional SSO credential parameters
*/
interface SsoCredentialsParameters {
clientName?: string;
clientType?: string;
}
/**
* Configuration options from @aws-sdk/credential-provider-web-identity
*/
interface FromTokenFileInit {
webIdentityTokenFile?: string;
roleArn?: string;
roleSessionName?: string;
roleAssumerWithWebIdentity?: (params: AssumeRoleWithWebIdentityParams) => Promise<AwsCredentialIdentity>;
logger?: Logger;
}
interface AssumeRoleParams {
roleArn: string;
roleSessionName?: string;
durationSeconds?: number;
externalId?: string;
policy?: string;
policyArns?: Array<{ arn?: string }>;
serialNumber?: string;
tokenCode?: string;
}
interface AssumeRoleWithWebIdentityParams {
roleArn: string;
roleSessionName?: string;
webIdentityToken: string;
durationSeconds?: number;
policy?: string;
policyArns?: Array<{ arn?: string }>;
providerId?: string;
}
type Provider<T> = T | (() => Promise<T>);The credential provider chain throws CredentialsProviderError when:
Common Error Scenarios:
import { defaultProvider } from "@aws-sdk/credential-provider-node";
try {
const credentials = await defaultProvider()();
} catch (error) {
if (error.name === "CredentialsProviderError") {
console.error("Could not load credentials:", error.message);
// Handle credential loading failure
}
}/**
* Error thrown when credential providers fail to provide credentials
*/
class CredentialsProviderError extends Error {
name: "CredentialsProviderError";
message: string;
tryNextLink?: boolean;
logger?: Logger;
constructor(message: string, options?: { tryNextLink?: boolean; logger?: Logger });
}Warning Cases:
AWS_PROFILE and AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY)AWS_EC2_METADATA_DISABLED environment variableThe provider respects several environment variables:
AWS_PROFILE - Configuration profile to useAWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY - Static credentialsAWS_SHARED_CREDENTIALS_FILE - Path to credentials fileAWS_CONFIG_FILE - Path to config fileAWS_ROLE_ARN - Role ARN for assumptionAWS_WEB_IDENTITY_TOKEN_FILE - Web identity token file pathAWS_EC2_METADATA_DISABLED - Disable IMDS access ("true" to disable)