The AWS SDK for JavaScript v2 is the official Amazon Web Services client library that provides unified access to 387 AWS services from JavaScript applications. It supports Node.js, browser, and React Native environments with comprehensive authentication, configuration, and request management capabilities.
npm install aws-sdkconst AWS = require('aws-sdk');For individual services (tree-shaking):
const S3 = require('aws-sdk/clients/s3');
const DynamoDB = require('aws-sdk/clients/dynamodb');
const Lambda = require('aws-sdk/clients/lambda');With ES6 modules:
import AWS from 'aws-sdk';
import S3 from 'aws-sdk/clients/s3';TypeScript:
import * as AWS from 'aws-sdk';
import { S3, DynamoDB, Lambda } from 'aws-sdk';const AWS = require('aws-sdk');
// Configure the SDK
AWS.config.update({
region: 'us-east-1',
accessKeyId: 'YOUR_ACCESS_KEY',
secretAccessKey: 'YOUR_SECRET_KEY'
});
// Use a service
const s3 = new AWS.S3();
const params = {
Bucket: 'my-bucket',
Key: 'my-file.txt',
Body: 'Hello World!'
};
s3.putObject(params, (err, data) => {
if (err) console.error(err);
else console.log('Upload successful:', data);
});
// With promises
s3.putObject(params).promise()
.then(data => console.log('Upload successful:', data))
.catch(err => console.error(err));The AWS SDK is built around several core components:
Global SDK configuration and credential management system supporting multiple authentication methods and environments.
const AWS = {
config: {
update(options: ConfigurationOptions): void;
getCredentials(callback: (err?: Error) => void): void;
region: string;
credentials: Credentials;
maxRetries: number;
httpOptions: HTTPOptions;
};
Credentials: new (accessKeyId: string, secretAccessKey: string, sessionToken?: string) => Credentials;
VERSION: string;
}Configuration & Authentication
Comprehensive collection of 387 AWS service clients with consistent interfaces for API operations, error handling, and response processing.
interface ServiceClient {
constructor(options?: ClientConfiguration);
config: Config & ClientConfiguration;
makeRequest(operation: string, params?: any, callback?: RequestCallback): Request;
// Each service has specific operations, e.g., for S3:
putObject(params: PutObjectRequest, callback?: Callback<PutObjectOutput>): Request<PutObjectOutput>;
getObject(params: GetObjectRequest, callback?: Callback<GetObjectOutput>): Request<GetObjectOutput>;
}Event-driven request lifecycle system with support for callbacks, promises, streaming, pagination, and comprehensive error handling.
interface Request<TData = any> {
promise(): Promise<Response<TData>>;
send(callback?: RequestCallback<TData>): void;
abort(): void;
createReadStream(): NodeJS.ReadableStream;
eachPage(callback: EachPageCallback): void;
on(event: string, listener: Function): Request<TData>;
}
interface Response<TData = any> {
data: TData;
error?: AWSError;
requestId: string;
hasNextPage(): boolean;
nextPage(callback?: RequestCallback): Request;
}Extensive utility library providing encoding, cryptographic functions, date handling, and AWS-specific operations.
const AWS = {
util: {
// Encoding & Decoding
base64: {
encode(string: string): string;
decode(string: string): string;
};
// Cryptographic Functions
crypto: {
hmac(key: any, string: string, digest?: string, fn?: Function): string | Buffer;
md5(data: any, digest?: string, callback?: Function): string | Buffer;
sha256(data: any, digest?: string, callback?: Function): string | Buffer;
};
// Date & Time
date: {
getDate(): Date;
iso8601(date?: Date): string;
rfc822(date?: Date): string;
unixTimestamp(date?: Date): number;
};
// Object Manipulation
update(obj1: any, obj2: any): any;
copy(object: any): any;
isEmpty(obj: any): boolean;
};
}Event-driven execution system used throughout the SDK for request lifecycle management and custom behavior injection.
interface SequentialExecutor {
on(eventName: string, listener: Function, toHead?: boolean): SequentialExecutor;
onAsync(eventName: string, listener: Function, toHead?: boolean): SequentialExecutor;
removeListener(eventName: string, listener: Function): SequentialExecutor;
emit(eventName: string, eventObject?: any, callback?: Function): void;
}
// Global events available on AWS.events
const AWS = {
events: SequentialExecutor;
}class Service {
constructor(config?: ClientConfiguration);
// Configuration
config: Config & ClientConfiguration;
endpoint: Endpoint;
// Core methods
makeRequest(operation: string, params?: any, callback?: RequestCallback): Request;
defineService(serviceIdentifier: string, versions: string[], features?: any): typeof Service;
addVersions(versions: string[]): void;
// Properties
api: ApiModel;
serviceIdentifier: string;
apiVersions: string[];
// Waiters
waitFor(state: string, params?: any, callback?: RequestCallback): Request;
}class HttpRequest {
constructor(endpoint: Endpoint, region?: string);
// Properties
method: string;
path: string;
headers: { [key: string]: string };
body?: string | Buffer | Uint8Array;
endpoint: Endpoint;
region: string;
// Methods
pathname(): string;
search(): string;
}
class HttpResponse {
constructor();
// Properties
statusCode?: number;
statusMessage?: string;
headers: { [key: string]: string };
body?: string | Buffer;
streaming: boolean;
// Methods
createUnbufferedStream(): any;
}class MetadataService {
constructor(options?: {
host?: string;
httpOptions?: HTTPOptions;
maxRetries?: number;
retryDelayOptions?: RetryDelayOptions;
});
// Methods
request(path: string, options?: any, callback?: (err: Error, data: any) => void): void;
loadCredentials(callback: (err: Error, credentials?: any) => void): void;
// Properties
httpOptions: HTTPOptions;
maxRetries: number;
host: string;
}class ResourceWaiter {
constructor(service: Service, state: string);
// Properties
service: Service;
state: string;
// Methods
wait(params?: any, callback?: RequestCallback): Request;
// Static methods
static register(service: string, state: string, config: WaiterConfiguration): void;
}
interface WaiterConfiguration {
operation: string;
delay?: number;
maxAttempts?: number;
acceptors: WaiterAcceptor[];
}
interface WaiterAcceptor {
expected: any;
matcher: string;
state: string;
argument?: string;
}interface ConfigurationOptions {
region?: string;
credentials?: Credentials | CredentialProviderChain | null;
endpoint?: string | Endpoint;
maxRetries?: number;
httpOptions?: HTTPOptions;
sslEnabled?: boolean;
paramValidation?: boolean | ParamValidationOptions;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
correctClockSkew?: boolean;
s3ForcePathStyle?: boolean;
s3BucketEndpoint?: boolean;
s3DisableBodySigning?: boolean;
useAccelerateEndpoint?: boolean;
useDualstackEndpoint?: boolean;
retryDelayOptions?: RetryDelayOptions;
logger?: Logger;
systemClockOffset?: number;
signatureVersion?: string;
signatureCache?: boolean;
accessKeyId?: string;
secretAccessKey?: string;
sessionToken?: string;
}
interface HTTPOptions {
proxy?: string;
agent?: any;
connectTimeout?: number;
timeout?: number;
xhrAsync?: boolean;
xhrWithCredentials?: boolean;
}
interface Credentials {
accessKeyId: string;
secretAccessKey: string;
sessionToken?: string;
expired: boolean;
expireTime?: Date;
needsRefresh(): boolean;
refresh(callback: (err?: Error) => void): void;
get(callback: (err?: Error) => void): void;
}
interface AWSError extends Error {
code: string;
time: Date;
requestId?: string;
statusCode?: number;
retryable?: boolean;
retryDelay?: number;
}
interface ClientConfiguration extends ConfigurationOptions {
apiVersion?: string;
apiVersions?: { [service: string]: string };
region?: string;
customUserAgent?: string;
}
type RequestCallback<TData = any> = (err: AWSError | null, data?: TData) => void;
type EachPageCallback = (err: AWSError | null, data?: any, done?: () => void) => void;
interface ParamValidationOptions {
min?: boolean;
max?: boolean;
pattern?: boolean;
enum?: boolean;
}
interface RetryDelayOptions {
customBackoff?: (retryCount: number, err?: Error) => number;
base?: number;
}
interface Logger {
write?: (chunk: any, encoding?: string) => void;
log?: (...messages: any[]) => void;
}
interface Endpoint {
protocol: string;
hostname: string;
port?: number;
host: string;
href: string;
}
interface ApiModel {
metadata: {
apiVersion: string;
endpointPrefix: string;
protocol: string;
serviceAbbreviation?: string;
serviceFullName: string;
serviceId: string;
signatureVersion: string;
uid: string;
xmlNamespace?: string;
};
operations: { [operation: string]: OperationModel };
shapes: { [shape: string]: ShapeModel };
}
interface OperationModel {
name: string;
http: {
method: string;
requestUri: string;
responseCode?: number;
};
input?: ShapeModel;
output?: ShapeModel;
errors?: ShapeModel[];
documentation?: string;
streaming?: boolean;
}
interface ShapeModel {
type: string;
members?: { [member: string]: ShapeModel };
required?: string[];
documentation?: string;
payload?: string;
streaming?: boolean;
location?: string;
locationName?: string;
}
interface Token {
token: string;
expireTime?: Date;
needsRefresh(): boolean;
refresh(callback: (err?: Error) => void): void;
get(callback: (err?: Error) => void): void;
}
interface CredentialProvider {
resolve(callback: (err?: Error, credentials?: Credentials) => void): void;
resolvePromise(): Promise<Credentials>;
}
interface TokenProvider {
resolve(callback: (err?: Error, token?: Token) => void): void;
resolvePromise(): Promise<Token>;
}
interface ARNComponents {
partition: string;
service: string;
region: string;
accountId: string;
resource: string;
resourceType?: string;
}
type CredentialProviderChain = {
providers: CredentialProvider[];
resolve(callback: (err?: Error, credentials?: Credentials) => void): void;
resolvePromise(): Promise<Credentials>;
}