S3 Bucket

A Stacktape Bucket creates an Amazon S3 bucket for storing files, images, backups, or any binary data. S3 offers 99.999999999% (eleven nines) durability with pay-per-use pricing — you pay only for storage used and data transferred. Buckets are the most common way to store unstructured data on AWS.

S3 pricing is pay-per-use with no minimum commitment — you pay for storage volume, requests, and data transfer out.

When to use

Use a Stacktape Bucket when you need to store and retrieve arbitrary files — user uploads, images, PDFs, backups, data exports, build artifacts, or application logs. S3 is the right choice for any unstructured data that doesn't need the query capabilities of a database.

Common bucket use cases:

  • User-uploaded content — profile images, documents, videos
  • Application assets — processed files, exports, generated reports
  • Data pipelines — raw input data, intermediate results, output files
  • Backups and archives — database snapshots, audit logs, compliance data
  • Frontend build output — deploy static assets alongside your API

When NOT to use

A Stacktape Bucket is general-purpose S3 storage. For specific use cases, other Stacktape resources are a better fit:

Use caseBetter option
Hosting a static website or SPAHostingBucket — includes CDN, SPA routing, and index document handling
Next.js, Astro, Nuxt, or other SSR appsNextjsWeb, AstroWeb, etc.
Structured or queryable dataRelationalDatabase or DynamoDbTable
Shared filesystem mounted by containersEfsFilesystem

Basic example

A Bucket with no configuration creates a private S3 bucket. All properties in BucketProps are optional — the simplest valid bucket is an empty object.

export default defineConfig(() => {
  const uploads = new Bucket({});

  return {
    resources: { uploads }
  };
});

This creates a private bucket. Only compute resources and entities with sufficient IAM permissions can access it. Use connectTo to grant your compute resources access.

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.

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

  return {
    resources: { assets }
  };
});

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.

export default defineConfig(() => {
  const publicAssets = new Bucket({
    accessibility: {
      accessibilityMode: 'public-read'
    }
  });

  return {
    resources: { publicAssets }
  };
});

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.

export default defineConfig(() => {
  const uploads = new Bucket({
    cors: {
      enabled: true,
      corsRules: [
        {
          allowedOrigins: ['https://myapp.com'],
          allowedMethods: ['GET', 'PUT'],
          allowedHeaders: ['*'],
          maxAge: 3600
        }
      ]
    }
  });

  return {
    resources: { uploads }
  };
});

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.

export default defineConfig(() => {
  const spa = new Bucket({
    directoryUpload: {
      directoryPath: './dist',
      headersPreset: 'single-page-app'
    },
    cdn: {
      enabled: true,
      rewriteRoutesForSinglePageApp: true
    }
  });

  return {
    resources: { spa }
  };
});

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.

When to enable: Enable a CDN when you serve assets directly to end-user browsers, especially if your users are geographically distributed or you expect high download volume. When the default is fine: For most buckets that only serve files to your own backend (Lambda functions, containers), adding a CDN introduces unnecessary complexity. Tradeoff: CDN adds a small per-request and data-transfer cost but typically pays for itself by reducing S3 bandwidth charges on high-traffic buckets.

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 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
export default defineConfig(() => {
  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
        }
      }
    ]
  });

  return {
    resources: { dataLake }
  };
});

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

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.

export default defineConfig(() => {
  const secureBucket = new Bucket({
    versioning: true,
    encryption: true,
    lifecycleRules: [
      {
        type: 'non-current-version-expiration',
        properties: {
          daysAfterVersioned: 30
        }
      }
    ]
  });

  return {
    resources: { secureBucket }
  };
});

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.

export default defineConfig(() => {
  const uploads = new Bucket({
    enableEventBusNotifications: true
  });

  return {
    resources: { uploads }
  };
});

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

Use connectTo to grant a compute resource (Lambda function, container workload, batch job) access to a bucket. connectTo grants bucket read, write, and delete object permissions, and injects environment variables with the bucket's name and ARN.

export default defineConfig(() => {
  const uploads = new Bucket({});

  const processor = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/processor.ts'
    }),
    connectTo: [uploads]
  });

  return {
    resources: { uploads, processor }
  };
});

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:

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' }) };
};

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.

The following parameters can be easily referenced using $ResourceParam directive directive.

To learn more about referencing parameters, refer to referencing parameters.

name
  • AWS (physical) name of the bucket

  • Usage: $ResourceParam('<<resource-name>>', 'name')
arn
  • Arn of the bucket

  • Usage: $ResourceParam('<<resource-name>>', 'arn')
cdnDomain
  • Default domain of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).

  • Usage: $ResourceParam('<<resource-name>>', 'cdnDomain')
cdnUrl
  • Default url of the CDN distribution (only available if you DO NOT configure custom domain names for the CDN).

  • Usage: $ResourceParam('<<resource-name>>', 'cdnUrl')
cdnCustomDomains
  • Comma-separated list of custom domain names assigned to the CDN (only available if you configure custom domain names for the CDN).

  • Usage: $ResourceParam('<<resource-name>>', 'cdnCustomDomains')
cdnCustomDomainUrls
  • Comma-separated list of custom domain name URLs of the CDN (only available if you configure custom domain names for the CDN).

  • Usage: $ResourceParam('<<resource-name>>', 'cdnCustomDomainUrls')

API Reference

BucketProps
Click a property in the tree to see its description, default value, and full type.

S3 Bucket FAQ

How do I upload files to an S3 bucket from my application code?

Use the AWS S3 SDK (available for every major language) with the bucket name from the STP_[RESOURCE_NAME]_NAME environment variable injected by connectTo. For example, a bucket resource named uploads injects STP_UPLOADS_NAME. For browser-based uploads, generate a presigned URL on your server and have the client upload directly to S3 — this avoids routing large files through your API. Enable CORS on the bucket when using presigned URLs from a browser.

How much does S3 storage cost, and how do I keep it down?

S3 uses pure pay-per-use pricing with no upfront costs or minimum commitments. You pay for storage volume (per GB/month), requests (per 1,000 GET/PUT operations), and data transfer out of AWS. Drive the bill down with lifecycle rules: transition infrequently accessed data to STANDARD_IA after 30 days, archive old data to GLACIER or DEEP_ARCHIVE, expire logs after a retention period, and add an abort-incomplete-multipart-upload rule to every bucket to stop failed uploads from accumulating invisible charges. For unpredictable access patterns, INTELLIGENT_TIERING auto-tiers objects based on actual usage. See Managing Costs for monitoring AWS spend.

When should I use a Bucket vs a HostingBucket?

Use a HostingBucket when you're deploying a static website or SPA to end users — it bundles a CDN, SPA routing, and optimized caching headers in one resource. Use a Bucket for backend storage: user uploads, data files, backups, or any files that aren't served directly as a website. If you need fine-grained control over CDN and caching behavior, a Bucket with a cdn configuration is also an option.

Can I attach a custom domain to a bucket?

BucketProps does not expose a top-level custom-domain setting. If you place the bucket behind a CDN with the cdn property, domain configuration belongs to the CDN layer — see the CDN and custom domains pages for details. For static sites that need a custom domain, HostingBucket is usually the simpler path.

How do I trigger a Lambda function when a file is uploaded?

Configure an S3 event trigger on your Lambda function. The trigger fires for the configured S3 event type — commonly object-created, object-removed, or object-restore events. You can filter by key prefix and suffix to trigger only for specific file types or paths. For fan-out to multiple consumers from the same event, enable enableEventBusNotifications and use EventBridge rules instead.

S3 vs EFS — when should I use each?

Use S3 (Bucket) for object storage — uploading, downloading, and processing individual files via the S3 API. Use EFS when containers need a shared POSIX filesystem that mounts like a local directory. EFS is appropriate for workloads that read and write files using standard file I/O (e.g., CMS media directories, shared config files across containers). S3 is cheaper per GB, more durable, and scales without capacity limits, but requires SDK-based access rather than filesystem calls.

Is data in S3 encrypted?

Setting encryption: true in your Stacktape bucket config configures AES-256 server-side encryption at rest on the bucket, as described by the BucketProps.encryption JSDoc: "Encrypt stored objects at rest (AES-256)." Data in transit to and from S3 is encrypted via HTTPS. BucketProps exposes only this AES-256 toggle. If you need different encryption (e.g., AWS KMS customer-managed keys), use overrides to modify the underlying CloudFormation resource — verify the generated template before deploying.