Skip to content

Resources / Storage

S3 bucket

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:

TypeScript
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.

Warning:

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.

TypeScript
const assets = new Bucket({  directoryUpload: {    directoryPath: './dist',    headersPreset: 'single-page-app'  }});

The headersPreset property sets optimized HTTP caching headers for your framework. Available presets:

PresetBehaviorBest for
single-page-appHTML never cached, hashed assets cached foreverReact, Vue, Angular SPAs
static-websiteCDN-cached, never browser-cachedGeneric static sites
astro-static-websiteHashed build assets cached forever, HTML always freshAstro static builds
sveltekit-static-websiteHashed build assets cached forever, HTML always freshSvelteKit static builds
nuxt-static-websiteHashed build assets cached forever, HTML always freshNuxt static builds
gatsby-static-websiteSupported Gatsby presetGatsby 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:

ModeWho can readWho can writeDefault
privateOnly resources with IAM permissionsOnly resources with IAM permissionsYes
public-readAnyone on the internetOnly resources with IAM permissionsNo
public-read-writeAnyone on the internetAnyone on the internetNo

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.

TypeScript
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.

TypeScript
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.

TypeScript
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.

Tip:

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 typeWhat it does
expirationDelete objects after a set number of days since upload
non-current-version-expirationDelete old object versions after a set number of days (requires versioning: true)
class-transitionMove objects to a cheaper storage class after a set number of days
non-current-version-class-transitionMove old versions to a cheaper storage class after they become non-current; use with versioning: true
abort-incomplete-multipart-uploadClean up incomplete multipart uploads after a set number of days
TypeScript
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 classAccess patternRetrieval speedBest for
STANDARD_IAInfrequent accessInstantBackups, older data you still query occasionally
ONEZONE_IAInfrequent, single AZInstant (less durable than multi-AZ)Reproducible data like thumbnails or transcoded media
INTELLIGENT_TIERINGUnknown or changingInstant (auto-tiered by AWS)Data with unpredictable access patterns
GLACIERArchiveMinutes to hoursCompliance archives, old logs
DEEP_ARCHIVELong-term archive12+ hoursData you rarely need but must retain for years
Tip:

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.

TypeScript
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.

TypeScript
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.

TypeScript
const processor = new LambdaFunction({  ...  connectTo: [uploads]});

The processor function receives these environment variables at runtime:

VariableDescription
STP_UPLOADS_NAMEThe S3 bucket name
STP_UPLOADS_ARNThe S3 bucket ARN

Use the bucket name with any AWS S3 SDK to read and write objects:

TypeScript
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, or public-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.

  • enableEventBusNotificationsbooleanDefault false

    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.

name

AWS (physical) name of the bucket

arn

Arn of the bucket

cdnDomain

Default domain of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).

cdnUrl

Default url of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).

cdnCustomDomains

Comma-separated list of custom domain names assigned to the CDN (only available if you configure custom domain names for the CDN).

cdnCustomDomainUrls

Comma-separated list of custom domain name URLs of the CDN (only available if you configure custom domain names for the CDN).

Next steps