0
# Bucket Operations
1
2
This document covers all bucket-related operations including creation, deletion, listing, and advanced bucket management features like policies, versioning, lifecycle, encryption, and replication.
3
4
## Basic Bucket Operations
5
6
### Create Bucket
7
8
```javascript { .api }
9
// Basic bucket creation
10
await client.makeBucket(bucketName, region?, makeOpts?)
11
12
// Parameters
13
bucketName: string // Bucket name (must follow S3 naming rules)
14
region?: string // AWS region (default: 'us-east-1')
15
makeOpts?: MakeBucketOpt // Additional options
16
```
17
18
#### MakeBucketOpt Interface
19
20
```typescript { .api }
21
interface MakeBucketOpt {
22
ObjectLocking?: boolean // Enable object locking (cannot be changed later)
23
}
24
```
25
26
#### Examples
27
28
```javascript { .api }
29
// Simple bucket creation
30
await client.makeBucket('my-bucket')
31
32
// Bucket with specific region
33
await client.makeBucket('my-bucket', 'us-west-2')
34
35
// Bucket with object locking enabled
36
await client.makeBucket('locked-bucket', 'us-east-1', {
37
ObjectLocking: true
38
})
39
```
40
41
### Check Bucket Exists
42
43
```javascript { .api }
44
const exists = await client.bucketExists(bucketName)
45
46
// Returns: Promise<boolean>
47
```
48
49
#### Example
50
51
```javascript { .api }
52
const bucketName = 'my-bucket'
53
if (await client.bucketExists(bucketName)) {
54
console.log('Bucket exists')
55
} else {
56
console.log('Bucket does not exist')
57
await client.makeBucket(bucketName)
58
}
59
```
60
61
### List Buckets
62
63
```javascript { .api }
64
const buckets = await client.listBuckets()
65
66
// Returns: Promise<BucketItemFromList[]>
67
```
68
69
#### BucketItemFromList Interface
70
71
```typescript { .api }
72
interface BucketItemFromList {
73
name: string // Bucket name
74
creationDate: Date // Creation timestamp
75
}
76
```
77
78
#### Example
79
80
```javascript { .api }
81
const buckets = await client.listBuckets()
82
buckets.forEach(bucket => {
83
console.log(`Bucket: ${bucket.name}, Created: ${bucket.creationDate}`)
84
})
85
```
86
87
### Delete Bucket
88
89
```javascript { .api }
90
await client.removeBucket(bucketName)
91
92
// Note: Bucket must be empty before deletion
93
```
94
95
#### Example with Error Handling
96
97
```javascript { .api }
98
try {
99
await client.removeBucket('my-bucket')
100
console.log('Bucket deleted successfully')
101
} catch (error) {
102
if (error.code === 'BucketNotEmpty') {
103
console.log('Bucket is not empty, delete all objects first')
104
// Delete all objects, then retry bucket deletion
105
}
106
}
107
```
108
109
### List Incomplete Uploads
110
111
Lists all incomplete multipart uploads in a bucket.
112
113
```javascript { .api }
114
const stream = client.listIncompleteUploads(bucketName, prefix?, recursive?)
115
116
// Parameters
117
bucketName: string // Bucket name
118
prefix?: string // Filter by object name prefix (default: '')
119
recursive?: boolean // List recursively (default: false)
120
121
// Returns: BucketStream<IncompleteUploadedBucketItem>
122
```
123
124
#### IncompleteUploadedBucketItem Interface
125
126
```typescript { .api }
127
interface IncompleteUploadedBucketItem {
128
key: string // Object name/key
129
uploadId: string // Upload ID of the incomplete upload
130
size: number // Current size of uploaded parts
131
}
132
```
133
134
#### Examples
135
136
```javascript
137
// List all incomplete uploads in bucket
138
const stream = client.listIncompleteUploads('my-bucket')
139
stream.on('data', (upload) => {
140
console.log('Incomplete upload:', upload.key, upload.uploadId, upload.size)
141
})
142
stream.on('end', () => console.log('Done listing incomplete uploads'))
143
stream.on('error', (err) => console.error('Error:', err))
144
145
// List incomplete uploads with prefix filter
146
const prefixStream = client.listIncompleteUploads('my-bucket', 'documents/')
147
prefixStream.on('data', (upload) => {
148
console.log('Found incomplete upload for:', upload.key)
149
})
150
151
// List all incomplete uploads recursively
152
const recursiveStream = client.listIncompleteUploads('my-bucket', '', true)
153
recursiveStream.on('data', (upload) => {
154
// Process each incomplete upload
155
console.log(`Incomplete: ${upload.key} (${upload.size} bytes)`)
156
})
157
```
158
159
## Bucket Policies
160
161
### Get Bucket Policy
162
163
```javascript { .api }
164
const policy = await client.getBucketPolicy(bucketName)
165
166
// Returns: Promise<string> - JSON policy string
167
```
168
169
### Set Bucket Policy
170
171
```javascript { .api }
172
await client.setBucketPolicy(bucketName, policy)
173
174
// Parameters
175
bucketName: string // Bucket name
176
policy: string // JSON policy string
177
```
178
179
#### Policy Examples
180
181
```javascript { .api }
182
// Read-only public policy
183
const readOnlyPolicy = {
184
"Version": "2012-10-17",
185
"Statement": [
186
{
187
"Effect": "Allow",
188
"Principal": {"AWS": "*"},
189
"Action": ["s3:GetObject"],
190
"Resource": ["arn:aws:s3:::my-bucket/*"]
191
}
192
]
193
}
194
195
await client.setBucketPolicy('my-bucket', JSON.stringify(readOnlyPolicy))
196
197
// Full public access policy
198
const publicPolicy = {
199
"Version": "2012-10-17",
200
"Statement": [
201
{
202
"Effect": "Allow",
203
"Principal": {"AWS": "*"},
204
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
205
"Resource": ["arn:aws:s3:::my-bucket/*"]
206
}
207
]
208
}
209
210
await client.setBucketPolicy('my-bucket', JSON.stringify(publicPolicy))
211
```
212
213
## Bucket Tagging
214
215
### Get Bucket Tags
216
217
```javascript { .api }
218
const tags = await client.getBucketTagging(bucketName)
219
220
// Returns: Promise<Tag[]>
221
```
222
223
### Set Bucket Tags
224
225
```javascript { .api }
226
await client.setBucketTagging(bucketName, tags)
227
228
// Parameters
229
bucketName: string // Bucket name
230
tags: Tags // Tag collection
231
```
232
233
### Remove Bucket Tags
234
235
```javascript { .api }
236
await client.removeBucketTagging(bucketName)
237
```
238
239
#### Tag Types
240
241
```typescript { .api }
242
interface Tag {
243
Key: string // Tag key
244
Value: string // Tag value
245
}
246
247
type Tags = Record<string, string> | Tag[] | TagList
248
249
interface TagList {
250
TagSet: Tag[]
251
}
252
```
253
254
#### Tagging Examples
255
256
```javascript { .api }
257
// Set tags using object syntax
258
await client.setBucketTagging('my-bucket', {
259
'Environment': 'production',
260
'Team': 'backend',
261
'Project': 'api-storage'
262
})
263
264
// Set tags using Tag array
265
await client.setBucketTagging('my-bucket', [
266
{ Key: 'Environment', Value: 'production' },
267
{ Key: 'Team', Value: 'backend' }
268
])
269
270
// Get and display tags
271
const tags = await client.getBucketTagging('my-bucket')
272
tags.forEach(tag => {
273
console.log(`${tag.Key}: ${tag.Value}`)
274
})
275
```
276
277
## Bucket Versioning
278
279
### Get Versioning Configuration
280
281
```javascript { .api }
282
const versionConfig = await client.getBucketVersioning(bucketName)
283
284
// Returns: Promise<BucketVersioningConfiguration>
285
```
286
287
### Set Versioning Configuration
288
289
```javascript { .api }
290
await client.setBucketVersioning(bucketName, versionConfig)
291
292
// Parameters
293
bucketName: string // Bucket name
294
versionConfig: BucketVersioningConfiguration // Versioning settings
295
```
296
297
#### BucketVersioningConfiguration Interface
298
299
```typescript { .api }
300
interface BucketVersioningConfiguration {
301
Status?: 'Enabled' | 'Suspended' // Versioning status
302
MfaDelete?: 'Enabled' | 'Disabled' // MFA delete requirement
303
}
304
```
305
306
#### Versioning Examples
307
308
```javascript { .api }
309
// Enable versioning
310
await client.setBucketVersioning('my-bucket', {
311
Status: 'Enabled'
312
})
313
314
// Suspend versioning (existing versions preserved)
315
await client.setBucketVersioning('my-bucket', {
316
Status: 'Suspended'
317
})
318
319
// Check current versioning status
320
const config = await client.getBucketVersioning('my-bucket')
321
console.log('Versioning status:', config.Status)
322
```
323
324
## Bucket Lifecycle Management
325
326
### Get Lifecycle Configuration
327
328
```javascript { .api }
329
const lifecycleConfig = await client.getBucketLifecycle(bucketName)
330
331
// Returns: Promise<LifecycleConfig | null>
332
```
333
334
### Set Lifecycle Configuration
335
336
```javascript { .api }
337
await client.setBucketLifecycle(bucketName, lifeCycleConfig)
338
339
// Parameters
340
bucketName: string // Bucket name
341
lifeCycleConfig: LifeCycleConfigParam // Lifecycle rules
342
```
343
344
### Remove Lifecycle Configuration
345
346
```javascript { .api }
347
await client.removeBucketLifecycle(bucketName)
348
```
349
350
#### Lifecycle Types
351
352
```typescript { .api }
353
interface LifeCycleConfigParam {
354
Rule: LifecycleRule[]
355
}
356
357
interface LifecycleRule {
358
ID?: string // Rule identifier
359
Status: 'Enabled' | 'Disabled' // Rule status
360
Filter?: { // Object filter
361
Prefix?: string // Prefix filter
362
Tag?: Tag // Tag filter
363
And?: { // Multiple filters
364
Prefix?: string
365
Tags?: Tag[]
366
}
367
}
368
Expiration?: { // Object expiration
369
Days?: number // Days after creation
370
Date?: string // Specific date
371
ExpiredObjectDeleteMarker?: boolean
372
}
373
NoncurrentVersionExpiration?: { // Non-current version expiration
374
NoncurrentDays: number // Days after becoming non-current
375
}
376
AbortIncompleteMultipartUpload?: { // Cleanup incomplete uploads
377
DaysAfterInitiation: number // Days after upload initiation
378
}
379
Transition?: { // Storage class transition
380
Days?: number // Days after creation
381
Date?: string // Specific date
382
StorageClass: string // Target storage class
383
}
384
NoncurrentVersionTransition?: { // Non-current version transition
385
NoncurrentDays: number // Days after becoming non-current
386
StorageClass: string // Target storage class
387
}
388
}
389
```
390
391
#### Lifecycle Examples
392
393
```javascript { .api }
394
// Delete objects after 30 days and cleanup incomplete uploads
395
const lifecycleConfig = {
396
Rule: [
397
{
398
ID: 'DeleteOldObjects',
399
Status: 'Enabled',
400
Filter: { Prefix: 'logs/' },
401
Expiration: { Days: 30 },
402
AbortIncompleteMultipartUpload: { DaysAfterInitiation: 7 }
403
},
404
{
405
ID: 'ArchiveData',
406
Status: 'Enabled',
407
Filter: { Prefix: 'archive/' },
408
Transition: { Days: 30, StorageClass: 'GLACIER' }
409
}
410
]
411
}
412
413
await client.setBucketLifecycle('my-bucket', lifecycleConfig)
414
```
415
416
## Bucket Encryption
417
418
### Get Encryption Configuration
419
420
```javascript { .api }
421
const encryptionConfig = await client.getBucketEncryption(bucketName)
422
423
// Returns: Promise<EncryptionConfig>
424
```
425
426
### Set Encryption Configuration
427
428
```javascript { .api }
429
await client.setBucketEncryption(bucketName, encryptionConfig?)
430
431
// Parameters
432
bucketName: string // Bucket name
433
encryptionConfig?: EncryptionConfig // Encryption settings (optional for default AES256)
434
```
435
436
### Remove Encryption Configuration
437
438
```javascript { .api }
439
await client.removeBucketEncryption(bucketName)
440
```
441
442
#### EncryptionConfig Interface
443
444
```typescript { .api }
445
interface EncryptionConfig {
446
Rule: EncryptionRule[]
447
}
448
449
interface EncryptionRule {
450
ApplyServerSideEncryptionByDefault: {
451
SSEAlgorithm: 'AES256' | 'aws:kms' // Encryption algorithm
452
KMSMasterKeyID?: string // KMS key ID (for KMS encryption)
453
}
454
}
455
```
456
457
#### Encryption Examples
458
459
```javascript { .api }
460
// Default AES256 encryption
461
await client.setBucketEncryption('my-bucket')
462
463
// Explicit AES256 encryption
464
const aes256Config = {
465
Rule: [{
466
ApplyServerSideEncryptionByDefault: {
467
SSEAlgorithm: 'AES256'
468
}
469
}]
470
}
471
await client.setBucketEncryption('my-bucket', aes256Config)
472
473
// KMS encryption with specific key
474
const kmsConfig = {
475
Rule: [{
476
ApplyServerSideEncryptionByDefault: {
477
SSEAlgorithm: 'aws:kms',
478
KMSMasterKeyID: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
479
}
480
}]
481
}
482
await client.setBucketEncryption('my-bucket', kmsConfig)
483
```
484
485
## Bucket Replication
486
487
### Get Replication Configuration
488
489
```javascript { .api }
490
const replicationConfig = await client.getBucketReplication(bucketName)
491
492
// Returns: Promise<ReplicationConfig>
493
```
494
495
### Set Replication Configuration
496
497
```javascript { .api }
498
await client.setBucketReplication(bucketName, replicationConfig)
499
500
// Parameters
501
bucketName: string // Source bucket name
502
replicationConfig: ReplicationConfigOpts // Replication settings
503
```
504
505
### Remove Replication Configuration
506
507
```javascript { .api }
508
await client.removeBucketReplication(bucketName)
509
```
510
511
#### Replication Types
512
513
```typescript { .api }
514
interface ReplicationConfigOpts {
515
Role: string // IAM role for replication
516
Rule: ReplicationRule[] // Replication rules
517
}
518
519
interface ReplicationRule {
520
ID?: string // Rule identifier
521
Status: 'Enabled' | 'Disabled' // Rule status
522
Priority?: number // Rule priority (higher numbers = higher priority)
523
DeleteMarkerReplication?: {
524
Status: 'Enabled' | 'Disabled'
525
}
526
Filter?: { // Object filter
527
Prefix?: string // Prefix filter
528
Tag?: Tag // Tag filter
529
And?: { // Multiple filters
530
Prefix?: string
531
Tags?: Tag[]
532
}
533
}
534
Destination: {
535
Bucket: string // Destination bucket ARN
536
StorageClass?: string // Storage class in destination
537
ReplicationTime?: { // Replication time control
538
Status: 'Enabled' | 'Disabled'
539
Time: { Minutes: number }
540
}
541
Metrics?: { // Replication metrics
542
Status: 'Enabled' | 'Disabled'
543
EventThreshold: { Minutes: number }
544
}
545
}
546
}
547
```
548
549
#### Replication Example
550
551
```javascript { .api }
552
const replicationConfig = {
553
Role: 'arn:aws:iam::123456789012:role/replication-role',
554
Rule: [{
555
ID: 'ReplicateAll',
556
Status: 'Enabled',
557
Priority: 1,
558
DeleteMarkerReplication: { Status: 'Enabled' },
559
Filter: { Prefix: '' }, // Replicate all objects
560
Destination: {
561
Bucket: 'arn:aws:s3:::destination-bucket',
562
StorageClass: 'STANDARD_IA'
563
}
564
}]
565
}
566
567
await client.setBucketReplication('source-bucket', replicationConfig)
568
```
569
570
## Object Lock Configuration
571
572
### Get Object Lock Configuration
573
574
```javascript { .api }
575
const lockConfig = await client.getObjectLockConfig(bucketName)
576
577
// Returns: Promise<ObjectLockInfo>
578
```
579
580
### Set Object Lock Configuration
581
582
```javascript { .api }
583
await client.setObjectLockConfig(bucketName, lockConfigOpts)
584
585
// Parameters
586
bucketName: string // Bucket name
587
lockConfigOpts: Omit<ObjectLockInfo, 'objectLockEnabled'> // Lock configuration
588
```
589
590
#### ObjectLockInfo Interface
591
592
```typescript { .api }
593
interface ObjectLockInfo {
594
objectLockEnabled: 'Enabled' | 'Disabled' // Object lock status (read-only)
595
rule?: { // Default retention rule
596
defaultRetention: {
597
mode: RETENTION_MODES // Governance or Compliance
598
days?: number // Retention period in days
599
years?: number // Retention period in years
600
validity?: RETENTION_VALIDITY_UNITS // DAYS or YEARS
601
}
602
}
603
}
604
```
605
606
#### Object Lock Example
607
608
```javascript { .api }
609
import { RETENTION_MODES, RETENTION_VALIDITY_UNITS } from 'minio'
610
611
// Note: Object locking must be enabled during bucket creation
612
await client.makeBucket('locked-bucket', 'us-east-1', {
613
ObjectLocking: true
614
})
615
616
// Set default retention rule
617
await client.setObjectLockConfig('locked-bucket', {
618
rule: {
619
defaultRetention: {
620
mode: RETENTION_MODES.GOVERNANCE,
621
days: 30,
622
validity: RETENTION_VALIDITY_UNITS.DAYS
623
}
624
}
625
})
626
627
// Check configuration
628
const lockInfo = await client.getObjectLockConfig('locked-bucket')
629
console.log('Object lock enabled:', lockInfo.objectLockEnabled)
630
console.log('Default retention:', lockInfo.rule?.defaultRetention)
631
```
632
633
## Bucket Notifications
634
635
See [Notifications](./notifications.md) for detailed documentation on bucket notification configuration.
636
637
## Error Handling
638
639
```javascript { .api }
640
import { S3Error, InvalidBucketNameError } from 'minio'
641
642
try {
643
await client.makeBucket('invalid..bucket..name')
644
} catch (error) {
645
if (error instanceof InvalidBucketNameError) {
646
console.error('Invalid bucket name:', error.message)
647
} else if (error instanceof S3Error) {
648
console.error('S3 Error:', error.code, error.message)
649
}
650
}
651
```
652
653
## Best Practices
654
655
### 1. Bucket Naming
656
- Use lowercase letters, numbers, and hyphens only
657
- Must be 3-63 characters long
658
- Cannot start or end with hyphens
659
- Cannot contain consecutive periods
660
- Must be globally unique (for AWS S3)
661
662
### 2. Security
663
- Always set appropriate bucket policies
664
- Enable versioning for important data
665
- Use object locking for compliance requirements
666
- Configure encryption for sensitive data
667
668
### 3. Performance
669
- Use lifecycle rules to manage storage costs
670
- Configure replication for disaster recovery
671
- Clean up incomplete multipart uploads
672
- Monitor bucket metrics and notifications
673
674
### 4. Management
675
- Use consistent tagging strategy
676
- Document bucket purposes and policies
677
- Regular policy and configuration reviews
678
- Monitor replication and lifecycle rule effectiveness
679
680
---
681
682
**Next:** [Object Operations](./object-operations.md) - Learn about basic object CRUD operations