Skip to content

Bucket

Source: src/AWS/S3/Bucket.ts

An S3 bucket for storing objects in AWS.

A bucket name is auto-generated from the app, stage, and logical ID unless you provide one explicitly via bucketName. Enable forceDestroy to allow Alchemy to empty the bucket before deleting it.

Basic Bucket

import * as S3 from "alchemy/AWS/S3";
const bucket = yield* S3.Bucket("my-bucket", {});

Bucket with a custom name

const bucket = yield* S3.Bucket("my-bucket", {
bucketName: "my-company-assets",
});

Bucket with force destroy

const bucket = yield* S3.Bucket("my-bucket", {
forceDestroy: true,
});

Versioning and encryption

const bucket = yield* S3.Bucket("my-bucket", {
versioning: "Enabled",
encryption: { sseAlgorithm: "AES256" },
});

Block all public access

const bucket = yield* S3.Bucket("my-bucket", {
publicAccessBlock: {
blockPublicAcls: true,
ignorePublicAcls: true,
blockPublicPolicy: true,
restrictPublicBuckets: true,
},
});

CORS and lifecycle rules

const bucket = yield* S3.Bucket("my-bucket", {
cors: [
{
AllowedMethods: ["GET"],
AllowedOrigins: ["*"],
AllowedHeaders: ["*"],
MaxAgeSeconds: 3000,
},
],
lifecycleRules: [
{
ID: "expire-old",
Status: "Enabled",
Filter: { Prefix: "logs/" },
Expiration: { Days: 30 },
},
],
});

Static website hosting

const bucket = yield* S3.Bucket("my-bucket", {
objectOwnership: "BucketOwnerPreferred",
website: {
indexDocument: { suffix: "index.html" },
errorDocument: { key: "error.html" },
},
});

Bind S3 operations in the init phase and use them in runtime handlers. Bindings inject the bucket name and grant scoped IAM permissions automatically.

Read and write objects

// init
const getObject = yield* S3.GetObject(bucket);
const putObject = yield* S3.PutObject(bucket);
return {
fetch: Effect.gen(function* () {
// runtime
yield* putObject({
Key: "hello.txt",
Body: "Hello, World!",
ContentType: "text/plain",
});
const response = yield* getObject({ Key: "hello.txt" });
return HttpServerResponse.text("OK");
}),
};

Delete an object

// init
const deleteObject = yield* S3.DeleteObject(bucket);

Subscribe to bucket events from the init phase. The subscription and Lambda invoke permissions are created automatically.

// init
yield* S3.consumeBucketEvents(bucket, {
events: ["s3:ObjectCreated:*"],
}, (stream) =>
stream.pipe(
Stream.runForEach((event) =>
Effect.log(`New object: ${event.key}`),
),
),
);