A bucket is an Amazon S3 bucket for files: user uploads, images, PDFs, exports, backups, data for pipelines. S3 keeps your files with eleven nines of durability and scales without limits.
You pay for what you store, the requests you make and the data you send out to the internet. In us-east-1, S3 Standard costs $0.023 per GB-month, uploads $0.005 per 1,000 and downloads $0.0004 per 1,000 requests (S3 pricing). Many small, frequently read files cost more in requests than in storage. For a website, use static hosting; for a directory that containers mount, an EFS file system.
Basic example
A bucket needs no properties:
export default defineConfig(() => { const uploads = new Bucket({}); return { resources: { uploads } };});The bucket is private: only workloads you connect with connectTo and IAM identities with
permission can read or write it.
Uploading files on deploy
The directoryUpload property syncs a local directory to the bucket on every deployment. Stacktape mirrors the directory exactly — files in the bucket that are not in the local directory get deleted.
Directory upload replaces all existing bucket contents. Do not use this for buckets that store user-uploaded or application-generated files. It is designed for deploying build output, static assets, or configuration files.
const assets = new Bucket({ directoryUpload: { directoryPath: './dist', headersPreset: 'single-page-app' }});The headersPreset property sets optimized HTTP caching headers for your framework. Available presets:
| Preset | Behavior | Best for |
|---|---|---|
single-page-app | HTML never cached, hashed assets cached forever | React, Vue, Angular SPAs |
static-website | CDN-cached, never browser-cached | Generic static sites |
astro-static-website | Hashed build assets cached forever, HTML always fresh | Astro static builds |
sveltekit-static-website | Hashed build assets cached forever, HTML always fresh | SvelteKit static builds |
nuxt-static-website | Hashed build assets cached forever, HTML always fresh | Nuxt static builds |
gatsby-static-website | Supported Gatsby preset | Gatsby builds |
For more control, use fileOptions to set custom HTTP headers and tags on files matching specific glob patterns. For example, set a long Cache-Control header on image files while keeping HTML files uncached. Use excludeFilesPatterns to skip specific files during upload.
S3 Transfer Acceleration is enabled by default for faster uploads from distant locations. Disable it with disableS3TransferAcceleration: true to avoid the small per-GB surcharge.
Access control
Bucket access control determines who can read from and write to the bucket. The accessibility.accessibilityMode property supports three modes:
| Mode | Who can read | Who can write | Default |
|---|---|---|---|
private | Only resources with IAM permissions | Only resources with IAM permissions | Yes |
public-read | Anyone on the internet | Only resources with IAM permissions | No |
public-read-write | Anyone on the internet | Anyone on the internet | No |
Most buckets should stay private. Use connectTo to grant your compute resources access — connectTo grants bucket read, write, and delete object permissions automatically. Use public-read only when you need to serve files directly to browsers without signed URLs. Avoid public-read-write unless you have a specific reason — it allows anyone on the internet to write to your bucket.
const publicAssets = new Bucket({ accessibility: { accessibilityMode: 'public-read' }});For fine-grained access control, use accessibility.accessPolicyStatements for advanced access configuration with bucket policy IAM role statements.
CORS
CORS (Cross-Origin Resource Sharing) configuration is needed when browsers make requests directly to your S3 bucket, for example uploading files via presigned URLs from a frontend app. If your application only accesses the bucket from server-side code (Lambda functions, containers), you don't need CORS.
Set cors.enabled: true without corsRules to use permissive defaults (* origins, all methods). Add corsRules to replace those defaults with explicit browser access rules for production.
const uploads = new Bucket({ cors: { enabled: true, corsRules: [ { allowedOrigins: ['https://myapp.com'], allowedMethods: ['GET', 'PUT'], allowedHeaders: ['*'], maxAge: 3600 } ] }});When corsRules are provided, they define the explicit browser access rules for your bucket. Each rule specifies allowedOrigins, allowedMethods, allowedHeaders, optional exposedResponseHeaders (headers accessible to browser JavaScript), and maxAge (how long in seconds browsers can cache preflight responses). Rules are evaluated in order; the first matching rule wins for each preflight request. Allowed methods can be GET, POST, PUT, PATCH, DELETE, HEAD, or * for any.
CDN
Placing a CDN (Amazon CloudFront) in front of a bucket reduces download latency for global users, lowers bandwidth costs (CloudFront data transfer is cheaper than direct S3 transfer), and enables edge caching for frequently accessed files. Configure it with the cdn property.
const spa = new Bucket({ ... cdn: { enabled: true, rewriteRoutesForSinglePageApp: true }});The rewriteRoutesForSinglePageApp option routes requests without a file extension (e.g., /about, /dashboard) to index.html, letting your SPA handle client-side routing. Requests with extensions (.js, .css, .png) serve the actual file. Enable rewriteRoutesForSinglePageApp only for browser-routed SPAs where URLs like /dashboard should load index.html. Leave it disabled for ordinary file buckets or assets where extensionless keys should be looked up as stored objects.
Bucket CDN URL normalization is enabled by default for clean HTML URLs. Disable it with disableUrlNormalization: true only when your bucket object keys intentionally rely on exact URL paths.
Enable it when browsers download files from the bucket, especially users far from your region. Buckets that only your
backend reads don't need it. To serve the files at your own domain, set cdn.customDomains; see
Custom domains.
The bucket cdn property adds bucket-specific options rewriteRoutesForSinglePageApp and disableUrlNormalization on top of the shared CDN configuration. See the CDN resource page for shared CDN options.
If you're building a static website or SPA with CDN, client-side routing, and custom domains, a HostingBucket bundles all of this in a single resource type.
Lifecycle rules
Lifecycle rules automate storage cost management by expiring objects, transitioning them to cheaper storage classes, or cleaning up incomplete uploads. Configure them with the lifecycleRules array.
Stacktape supports five lifecycle rule types:
| Rule type | What it does |
|---|---|
expiration | Delete objects after a set number of days since upload |
non-current-version-expiration | Delete old object versions after a set number of days (requires versioning: true) |
class-transition | Move objects to a cheaper storage class after a set number of days |
non-current-version-class-transition | Move old versions to a cheaper storage class after they become non-current; use with versioning: true |
abort-incomplete-multipart-upload | Clean up incomplete multipart uploads after a set number of days |
const dataLake = new Bucket({ lifecycleRules: [ { type: 'class-transition', properties: { daysAfterUpload: 30, storageClass: 'STANDARD_IA', prefix: 'logs/' } }, { type: 'expiration', properties: { daysAfterUpload: 365, prefix: 'logs/' } }, { type: 'abort-incomplete-multipart-upload', properties: { daysAfterInitiation: 7 } } ]});This example moves log files to cheaper storage after 30 days, deletes them after a year, and cleans up failed multipart uploads after 7 days. Each rule supports optional prefix and tags filters to target specific objects.
Storage classes
The storageClass property in transition rules determines where objects move. Cheaper classes have higher retrieval costs or latency:
| Storage class | Access pattern | Retrieval speed | Best for |
|---|---|---|---|
STANDARD_IA | Infrequent access | Instant | Backups, older data you still query occasionally |
ONEZONE_IA | Infrequent, single AZ | Instant (less durable than multi-AZ) | Reproducible data like thumbnails or transcoded media |
INTELLIGENT_TIERING | Unknown or changing | Instant (auto-tiered by AWS) | Data with unpredictable access patterns |
GLACIER | Archive | Minutes to hours | Compliance archives, old logs |
DEEP_ARCHIVE | Long-term archive | 12+ hours | Data you rarely need but must retain for years |
Add an abort-incomplete-multipart-upload rule to every bucket. Large file uploads that fail midway leave invisible partial objects that accumulate storage charges. A 7-day cleanup rule prevents this waste.
Versioning and encryption
Versioning keeps previous versions of overwritten or deleted objects, letting you recover from accidental changes. Enable it with versioning: true. Versioning is a prerequisite for non-current-version-expiration and non-current-version-class-transition lifecycle rules. Enable versioning for buckets where accidental overwrites would be costly — user uploads, application data, configuration files. Skip it for ephemeral data like logs or build caches where old versions have no value. Note that versioning increases storage costs since all object versions are retained until explicitly expired by a lifecycle rule.
Encryption sets encryption: true to configure AES-256 server-side encryption at rest on the bucket. The source JSDoc describes this as "Encrypt stored objects at rest (AES-256)." If you need different encryption (e.g., AWS KMS customer-managed keys), use overrides on the underlying CloudFormation resource.
const secureBucket = new Bucket({ versioning: true, encryption: true, lifecycleRules: [ { type: 'non-current-version-expiration', properties: { daysAfterVersioned: 30 } } ]});When versioning is enabled, pair it with a non-current-version-expiration rule to automatically clean up old versions and avoid unbounded storage growth. In this example, old versions are deleted 30 days after they become non-current (i.e., after a newer version replaces them).
Event-driven workflows
Stacktape buckets support two approaches for reacting to object changes:
S3 event triggers invoke a Lambda function directly for configured S3 event types — commonly object-created, object-removed, and object-restore events. The trigger type also supports replication-related and reduced-redundancy lost-object events through the S3 trigger configuration. This is the simplest approach for processing uploads, for example resizing images or parsing CSV files. Configure S3 triggers on the Lambda function side.
EventBridge notifications send bucket events to EventBridge, where multiple consumers can react to the same event independently. Enable with enableEventBusNotifications: true (defaults to false). Use EventBridge notifications when bucket events should be available on EventBridge for other parts of your architecture. For direct upload processing, an S3 trigger on a Lambda function is usually simpler.
const uploads = new Bucket({ enableEventBusNotifications: true});For most use cases, an S3 event trigger on a Lambda function is simpler and sufficient. Choose EventBridge when you need fan-out to multiple consumers or complex event routing rules.
Connecting to a bucket
Add the bucket to a workload's connectTo. The workload can then read, write and
delete objects and gets the bucket's name and ARN as environment variables.
const processor = new LambdaFunction({ ... connectTo: [uploads]});The processor function receives these environment variables at runtime:
| Variable | Description |
|---|---|
STP_UPLOADS_NAME | The S3 bucket name |
STP_UPLOADS_ARN | The S3 bucket ARN |
Use the bucket name with any AWS S3 SDK to read and write objects:
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';const s3 = new S3Client({});export default async () => { await s3.send(new PutObjectCommand({ Bucket: process.env.STP_UPLOADS_NAME, Key: 'example.txt', Body: 'Hello from Stacktape' })); return { statusCode: 200, body: JSON.stringify({ message: 'Uploaded' }) };};For uploads from a browser, generate a presigned URL in your backend and let the browser upload straight to S3, so large files don't pass through your API. That needs CORS on the bucket. To run code when a file arrives, see Event-driven workflows.
Configuration reference
BucketProps8 properties- accessibilityBucketAccessibility
Who can read/write to this bucket:
private(default),public-read, orpublic-read-write. - cdnBucketCdnConfiguration
Put a CDN (CloudFront) in front of this bucket for faster downloads and lower bandwidth costs.
- corsBucketCorsConfig
CORS settings for browser-based access to the bucket.
- directoryUploadDirectoryUpload
Sync a local directory to this bucket on every deploy.
Send events (object created, deleted, etc.) to EventBridge for event-driven workflows.
- encryptionboolean
Encrypt stored objects at rest (AES-256).
Auto-delete or move objects to cheaper storage classes over time.
- versioningboolean
Keep previous versions of overwritten/deleted objects. Helps recover from mistakes.
Referenceable parameters
Use $ResourceParam to reference bucket properties in other parts of your config, for example passing the bucket name as an environment variable or using the ARN in a custom IAM policy.
Reference these parameters with the $ResourceParam directive: $ResourceParam('<resource-name>', '<parameter>'). See referenceable parameters.
nameAWS (physical) name of the bucket
arnArn of the bucket
cdnDomainDefault domain of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).
cdnUrlDefault url of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).
cdnCustomDomainsComma-separated list of custom domain names assigned to the CDN (only available if you configure custom domain names for the CDN).
cdnCustomDomainUrlsComma-separated list of custom domain name URLs of the CDN (only available if you configure custom domain names for the CDN).
Next steps
- S3 events: process files as they arrive.
- Static hosting: host a frontend from a bucket.
- Connecting resources: the variables and permissions
connectToadds.