or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cognito-credentials.mdconfiguration-file-credentials.mdcustom-credential-chains.mddefault-provider-chain.mdenvironment-credentials.mdhttp-credentials.mdindex.mdmetadata-service-credentials.mdprocess-credentials.mdsso-credentials.mdtemporary-credentials.mdweb-identity-credentials.md
tile.json

default-provider-chain.mddocs/

Default Node.js Provider Chain

Default Node.js provider chain is a comprehensive credential provider that tries multiple credential sources in order, including all common credential sources with sensible defaults and automatic role assumption.

Capabilities

Default Provider Chain

The credential provider used as default in Node.js SDK clients, with built-in role assumers.

/**
 * The default credential provider chain for Node.js environments with automatic role assumption
 * @param init - Configuration options for the provider chain
 * @returns Default Node.js credential provider function
 */
function fromNodeProviderChain(init?: DefaultProviderInit): AwsCredentialIdentityProvider;

interface DefaultProviderInit {
  /** Configuration profile name */
  profile?: string;
  /** Path to shared credentials file */
  filepath?: string;
  /** Path to shared config file */
  configFilepath?: string;
  /** Whether to ignore credential cache */
  ignoreCache?: boolean;
  /** SSO start URL for SSO credential resolution */
  ssoStartUrl?: string;
  /** SSO account ID */
  ssoAccountId?: string;
  /** SSO region */
  ssoRegion?: string;
  /** SSO role name */
  ssoRoleName?: string;
  /** Function that returns MFA token code */
  mfaCodeProvider?: (mfaSerial: string) => Promise<string>;
  /** Custom STS client configurations */
  clientConfig?: STSClientConfig;
  /** Custom STS client middleware plugins */
  clientPlugins?: Pluggable<any, any>[];
}

Usage Examples:

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

// Basic usage (most common)
const client = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain()
});

// With custom configuration
const customClient = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain({
    profile: "development",
    ignoreCache: true,
    mfaCodeProvider: async (mfaSerial) => {
      return await promptForMFAToken(mfaSerial);
    }
  })
});

Provider Chain Order

The default provider chain tries credential sources in this order:

  1. Environment Variables - AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  2. SSO Credentials - From cached SSO token
  3. Web Identity Token - From AWS_WEB_IDENTITY_TOKEN_FILE
  4. Shared Configuration Files - ~/.aws/credentials and ~/.aws/config
  5. Process Credentials - From credential_process configuration
  6. Instance Metadata Service - EC2 instance metadata (IMDS)
  7. Container Metadata Service - ECS container metadata
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

// This automatically tries all providers in order:
const credentials = fromNodeProviderChain({
  // Options apply to all applicable providers in the chain
  profile: "default",
  clientConfig: { region: "us-east-1" }
});

Environment-Specific Behavior

The chain adapts to different AWS environments:

Local Development

// Typically resolves to environment variables or INI files
const devClient = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain({
    profile: "development"
  })
});

EC2 Instances

// Automatically uses instance metadata when available
const ec2Client = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain() // Uses instance role
});

ECS/Fargate Containers

// Automatically uses container metadata when available
const ecsClient = new S3Client({
  region: process.env.AWS_REGION,
  credentials: fromNodeProviderChain() // Uses task role
});

Lambda Functions

// Uses Lambda's built-in credentials via environment variables
const lambdaClient = new S3Client({
  region: process.env.AWS_REGION,
  credentials: fromNodeProviderChain() // Uses execution role
});

Automatic Role Assumption

Unlike manual credential chains, the default provider includes built-in role assumers:

// Configuration in ~/.aws/config
// [profile assume-role]
// role_arn = arn:aws:iam::123456789012:role/MyRole
// source_profile = default

const client = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain({
    profile: "assume-role" // Automatically assumes the role
  })
});

SSO Integration

Full SSO support without additional configuration:

// SSO profile in ~/.aws/config
// [profile sso]
// sso_start_url = https://d-1234567890.awsapps.com/start
// sso_region = us-east-1
// sso_account_id = 123456789012
// sso_role_name = DeveloperAccess

const ssoClient = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain({
    profile: "sso" // Automatically uses SSO credentials
  })
});

Web Identity Token Support

Automatic support for Kubernetes service accounts and OIDC:

// Environment variables set by Kubernetes/EKS:
// AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token
// AWS_ROLE_ARN=arn:aws:iam::123456789012:role/EKSServiceRole

const k8sClient = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain() // Automatically uses web identity token
});

Credential Caching

The default provider includes intelligent caching:

// Cached credentials are reused until near expiration
const provider = fromNodeProviderChain();

// First call may be slow (credential resolution)
const credentials1 = await provider();

// Subsequent calls use cached credentials
const credentials2 = await provider(); // Fast

// Disable caching if needed
const nonCachedProvider = fromNodeProviderChain({
  ignoreCache: true // Always fetch fresh credentials
});

MFA Support

Built-in MFA support for profiles requiring multi-factor authentication:

import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

const mfaClient = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain({
    profile: "mfa-profile",
    mfaCodeProvider: async (mfaSerial) => {
      console.log(`Enter MFA token for ${mfaSerial}:`);
      // Implement your MFA token collection logic
      return await getMFATokenFromUser();
    }
  })
});

async function getMFATokenFromUser(): Promise<string> {
  // Example implementations:
  // - CLI prompt with readline
  // - GUI dialog
  // - Hardware token reader
  // - Time-based token generator
  return "123456"; // 6-digit MFA code
}

Custom Configuration Paths

Override default file locations:

import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

const customPathClient = new S3Client({
  region: "us-east-1",
  credentials: fromNodeProviderChain({
    filepath: "/custom/aws/credentials",
    configFilepath: "/custom/aws/config",
    profile: "custom-profile"
  })
});

Error Handling and Debugging

The provider chain provides detailed error information:

import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

try {
  const credentials = await fromNodeProviderChain()();
  console.log("Credentials resolved successfully");
} catch (error) {
  console.error("All credential providers failed:", error.message);
  
  // Common failure scenarios:
  if (error.message.includes('Could not load credentials from any providers')) {
    console.error('No valid credential sources found');
    console.error('Try: aws configure or set AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY');
  }
}

Performance Optimization

The chain stops at the first successful provider:

// Optimize by ensuring fastest providers are available:
// 1. Set environment variables for fastest resolution
// 2. Use instance/container metadata in AWS environments  
// 3. Configure profiles appropriately for your use case

const optimizedProvider = fromNodeProviderChain({
  // Only specify options that apply to your use case
  profile: process.env.AWS_PROFILE || "default"
});

Client Configuration Inheritance

The provider respects client-level configuration:

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

// Client profile takes precedence (v3.714.0+)
const client = new S3Client({
  profile: "client-profile", // Used by credential provider
  region: "us-east-1",
  credentials: fromNodeProviderChain() // Inherits client profile
});

// Explicit provider profile overrides client profile
const explicitClient = new S3Client({
  profile: "client-profile",
  region: "us-east-1",
  credentials: fromNodeProviderChain({
    profile: "provider-profile" // This takes precedence
  })
});

Comparison with Manual Chains

Default Provider Chain:

  • ✅ Includes all common credential sources
  • ✅ Automatic role assumption
  • ✅ Built-in SSO support
  • ✅ Web identity token support
  • ✅ Intelligent caching
  • ✅ Production-ready defaults

Manual createCredentialChain:

  • ✅ Full control over provider order
  • ✅ Custom provider integration
  • ✅ Explicit dependency management
  • ⚠️ Manual role assumer setup required
  • ⚠️ Manual SSO integration required

Use Cases

Use Default Provider Chain when:

  • Building standard AWS applications
  • Want automatic credential resolution
  • Need production-ready credential handling
  • Working in multiple AWS environments

Use Manual Chain when:

  • Need specific provider ordering
  • Integrating custom credential sources
  • Want explicit control over credential resolution
  • Building credential provider libraries

Availability

  • Node.js: ✅ Available (full feature set)
  • Browser: ❌ Not available (Node.js specific)
  • React Native: ❌ Not available