CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-minio

S3 Compatible Cloud Storage client for JavaScript/TypeScript

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

client-setup.mddocs/

Client Setup

This document covers client initialization, configuration options, and credential management for the MinIO JavaScript client.

Client Class

The main Client class extends TypedClient and provides the primary interface for all MinIO operations.

Constructor

import { Client } from 'minio'

const client = new Client(options)

ClientOptions Interface

interface ClientOptions {
  // Required
  endPoint: string              // MinIO server hostname or IP
  
  // Authentication (choose one method)
  accessKey?: string            // Access key for authentication
  secretKey?: string            // Secret key for authentication
  credentialsProvider?: CredentialProvider  // Dynamic credential provider
  
  // Connection settings
  useSSL?: boolean             // Use HTTPS (default: true for port 443)
  port?: number               // Server port (default: 443 for HTTPS, 80 for HTTP)
  region?: string             // AWS region (default: 'us-east-1')
  
  // Advanced options
  sessionToken?: string        // Temporary session token
  partSize?: number           // Multipart upload part size (min: 5MB)
  pathStyle?: boolean         // Use path-style URLs (default: false)
  s3AccelerateEndpoint?: string // S3 transfer acceleration endpoint
  transport?: Transport       // Custom HTTP transport
  transportAgent?: http.Agent // HTTP agent for connection pooling
}

Basic Client Setup

Simple Configuration

import { Client } from 'minio'

// Basic setup with access keys
const minioClient = new Client({
  endPoint: 'play.min.io',
  port: 9000,
  useSSL: true,
  accessKey: 'Q3AM3UQ867SPQQA43P2F',
  secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG'
})

Production Configuration

import { Client } from 'minio'
import * as https from 'node:https'

const minioClient = new Client({
  endPoint: 'minio.mycompany.com',
  port: 443,
  useSSL: true,
  accessKey: process.env.MINIO_ACCESS_KEY,
  secretKey: process.env.MINIO_SECRET_KEY,
  region: 'us-west-2',
  partSize: 64 * 1024 * 1024, // 64MB parts for large uploads
  
  // Connection pooling for better performance
  transportAgent: new https.Agent({
    keepAlive: true,
    maxSockets: 10,
    timeout: 60000
  })
})

Browser Configuration

// Browser environment - no file system operations
const minioClient = new Client({
  endPoint: 'play.min.io',
  port: 9000,
  useSSL: true,
  accessKey: 'Q3AM3UQ867SPQQA43P2F',
  secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG'
})

// Note: fPutObject and fGetObject are not available in browser

Credential Providers

The MinIO client supports multiple authentication methods through credential providers.

CredentialProvider Base Class

import { CredentialProvider, Credentials } from 'minio'

class CredentialProvider {
  constructor(options: {
    accessKey?: string
    secretKey?: string  
    sessionToken?: string
  })
  
  // Methods
  async getCredentials(): Promise<Credentials>
  setCredentials(credentials: Credentials): void
  setAccessKey(accessKey: string): void
  getAccessKey(): string
  setSecretKey(secretKey: string): void
  getSecretKey(): string
  setSessionToken(sessionToken: string): void
  getSessionToken(): string
}

Credentials Class

class Credentials {
  constructor(options: {
    accessKey: string
    secretKey: string
    sessionToken?: string
  })
  
  // Properties
  accessKey: string
  secretKey: string
  sessionToken?: string
  
  // Methods
  setAccessKey(accessKey: string): void
  getAccessKey(): string
  setSecretKey(secretKey: string): void
  getSecretKey(): string
  setSessionToken(sessionToken: string): void
  getSessionToken(): string
  get(): Credentials
}

AssumeRoleProvider

For AWS STS AssumeRole authentication:

import { AssumeRoleProvider } from 'minio'

interface AssumeRoleProviderOptions {
  stsEndpoint: string           // STS endpoint URL
  accessKey: string            // Initial access key
  secretKey: string            // Initial secret key
  durationSeconds?: number     // Session duration (900-43200 seconds)
  sessionToken?: string        // Existing session token
  policy?: string             // IAM policy for session
  region?: string             // AWS region
  roleArn?: string            // Role ARN to assume
  roleSessionName?: string    // Session name for the role
  externalId?: string         // External ID for role assumption
  token?: string              // MFA token
  webIdentityToken?: string   // Web identity token
  action?: string             // STS action (default: AssumeRole)
  transportAgent?: http.Agent // HTTP agent
}

// Usage
const assumeRoleProvider = new AssumeRoleProvider({
  stsEndpoint: 'https://sts.amazonaws.com',
  accessKey: 'your-access-key',
  secretKey: 'your-secret-key',
  roleArn: 'arn:aws:iam::123456789012:role/MyRole',
  roleSessionName: 'MinIOSession',
  durationSeconds: 3600
})

const client = new Client({
  endPoint: 's3.amazonaws.com',
  credentialsProvider: assumeRoleProvider
})

IamAwsProvider

For EC2/ECS IAM role credentials:

import { IamAwsProvider } from 'minio'

interface IamAwsProviderOptions {
  customEndpoint?: string     // Custom metadata endpoint
  transportAgent?: http.Agent // HTTP agent
}

// Usage - automatic IAM role detection
const iamProvider = new IamAwsProvider()

const client = new Client({
  endPoint: 's3.amazonaws.com', 
  credentialsProvider: iamProvider
})

// With custom endpoint (for testing)
const customIamProvider = new IamAwsProvider({
  customEndpoint: 'http://169.254.169.254'
})

Dynamic Credential Updates

// Update credentials at runtime
const credentialProvider = new CredentialProvider({
  accessKey: 'initial-key',
  secretKey: 'initial-secret'
})

const client = new Client({
  endPoint: 'play.min.io',
  credentialsProvider: credentialProvider
})

// Later, update credentials
await client.setCredentialsProvider(new CredentialProvider({
  accessKey: 'new-access-key',
  secretKey: 'new-secret-key',
  sessionToken: 'session-token'
}))

Advanced Configuration

Custom Transport

import * as https from 'node:https'

// Custom HTTPS agent with specific settings
const customAgent = new https.Agent({
  keepAlive: true,
  maxSockets: 25,
  maxFreeSockets: 10,
  timeout: 30000,
  freeSocketTimeout: 4000,
  // Custom certificate settings if needed
  rejectUnauthorized: false // Only for development!
})

const client = new Client({
  endPoint: 'minio.internal.com',
  port: 9000,
  useSSL: true,
  accessKey: process.env.MINIO_ACCESS_KEY,
  secretKey: process.env.MINIO_SECRET_KEY,
  transportAgent: customAgent
})

Path-Style URLs

// Force path-style URLs (bucket in path, not subdomain)
const client = new Client({
  endPoint: 'localhost',
  port: 9000,
  useSSL: false,
  accessKey: 'minioadmin',
  secretKey: 'minioadmin',
  pathStyle: true // URLs like http://localhost:9000/bucket/object
})

S3 Transfer Acceleration

const client = new Client({
  endPoint: 's3.amazonaws.com',
  useSSL: true,
  accessKey: process.env.AWS_ACCESS_KEY_ID,
  secretKey: process.env.AWS_SECRET_ACCESS_KEY,
  s3AccelerateEndpoint: 's3-accelerate.amazonaws.com'
})

// Or set it after client creation
client.setS3TransferAccelerate('s3-accelerate.amazonaws.com')

Client Utility Methods

Application Information

// Set application info for user agent
client.setAppInfo('MyApp', '1.2.3')

Request Options

import * as https from 'node:https'

// Set global request options
client.setRequestOptions({
  timeout: 30000,
  headers: {
    'X-Custom-Header': 'custom-value'
  }
})

Debugging and Tracing

import * as fs from 'node:fs'

// Enable request/response tracing to console
client.traceOn()

// Enable tracing to file
const logStream = fs.createWriteStream('minio-trace.log')
client.traceOn(logStream)

// Disable tracing
client.traceOff()

MinIO Extensions

The client provides access to MinIO-specific extensions that are not part of standard S3:

// Access MinIO-specific extensions
const extensions = client.extensions

// MinIO extensions provide additional functionality
// not available in standard S3 implementations
console.log('MinIO Extensions available:', extensions)

Environment Variables

Common environment variables for configuration:

# Basic authentication
export MINIO_ACCESS_KEY=your-access-key
export MINIO_SECRET_KEY=your-secret-key

# AWS credentials (for S3)
export AWS_ACCESS_KEY_ID=your-aws-key
export AWS_SECRET_ACCESS_KEY=your-aws-secret
export AWS_SESSION_TOKEN=your-session-token
export AWS_REGION=us-east-1

# MinIO server settings  
export MINIO_ENDPOINT=play.min.io
export MINIO_PORT=9000
export MINIO_USE_SSL=true

Error Handling

import { 
  Client, 
  S3Error, 
  InvalidArgumentError,
  InvalidBucketNameError 
} from 'minio'

try {
  const client = new Client({
    endPoint: 'invalid-endpoint',
    accessKey: 'test',
    secretKey: 'test'
  })
} catch (error) {
  if (error instanceof InvalidArgumentError) {
    console.error('Invalid client configuration:', error.message)
  }
}

// Runtime operation errors
try {
  await client.listBuckets()
} catch (error) {
  if (error instanceof S3Error) {
    console.error('S3 Error:', error.code, error.message)
    console.error('Region:', error.region)
  }
}

Best Practices

1. Credential Security

  • Never hardcode credentials in source code
  • Use environment variables or credential providers
  • Rotate credentials regularly
  • Use IAM roles when possible (EC2/ECS)

2. Performance Optimization

  • Configure appropriate connection pooling
  • Use multipart uploads for large files (set partSize)
  • Enable keep-alive connections
  • Consider S3 Transfer Acceleration for global applications

3. Error Handling

  • Always handle credential expiration
  • Implement retry logic for network errors
  • Validate bucket and object names before operations
  • Log errors appropriately for debugging

4. Resource Management

  • Close streams properly
  • Handle backpressure in streaming operations
  • Use appropriate timeouts
  • Monitor connection pool usage

Next: Bucket Operations - Learn about bucket management and configuration

docs

advanced-objects.md

bucket-operations.md

client-setup.md

index.md

notifications.md

object-operations.md

presigned-operations.md

types-and-errors.md

tile.json