Buckets (S3)



Buckets provide a way to store and retrieve any amount of data, at any time, from anywhere on the web. They are a good choice for a variety of use cases, including hosting websites, storing user-generated content, and for backup and disaster recovery.

A bucket is a collection of objects, where an object is a file and any metadata that describes it. Buckets have a flat structure, but you can simulate a folder hierarchy by using a common prefix for your object names (e.g., photos/).

Under the hood, Stacktape uses Amazon S3 for buckets.

When to use them

Buckets are ideal for storing large amounts of data. They are not recommended for use cases that require very low read/write latency.

Advantages

  • Easy to use: S3 provides a simple, HTTP-based API.
  • Serverless: Buckets scale automatically, and you only pay for what you use.
  • Highly available and durable: S3 is designed for 99.999999999% (eleven 9s) of data durability, storing objects across multiple Availability Zones.
  • Flexible storage classes: You can choose from multiple storage classes with different latencies, prices, and durability characteristics.
  • Access control: You can easily control who can access your bucket.
  • Encryption: Supports server-side encryption.
  • Integrations: You can trigger a function or a batch job in response to bucket events.

Disadvantages

  • Performance: Read and write operations are significantly slower than with block storage (a physical disk attached to a machine).

Basic usage

resources:
  myBucket:
    type: bucket

  myFunction:
    type: function
    properties:
      packaging:
        type: stacktape-lambda-buildpack
        properties:
          entryfilePath: path/to/my/lambda.ts
      environment:
        - name: BUCKET_NAME
          value: $ResourceParam('myBucket', 'arn')
      connectTo:
        - myBucket

A Lambda function connected to a bucket.

import { S3 } from '@aws-sdk/client-s3';

const s3 = new S3({});

// getObject returns a readable stream, so we need to transform it to string
const streamToString = (stream) => {
  const chunks = [];
  return new Promise((resolve, reject) => {
    stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
    stream.on('error', (err) => reject(err));
    stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
  });
};

const handler = async (event, context) => {
  await s3.putObject({
    Bucket: process.env.BUCKET_NAME,
    Key: 'my-file.json',
    Body: JSON.stringify({ message: 'hello' }) // or fs.createReadStream('my-source-file.json')
  });

  const res = await s3.getObject({
    Bucket: process.env.BUCKET_NAME,
    Key: 'my-file.json'
  });
  const body = await streamToString(res.Body);
};

export default handler;

A Lambda function that uploads and downloads a file from a bucket.

Directory upload

You can automatically upload the contents of a local directory to a bucket during deployment.

Warning: Replaces all existing bucket contents. Don't use for buckets with user-uploaded or application-generated files.

resources:
  myBucket:
    type: bucket
    properties:
      directoryUpload:
        directoryPath: ../public

This configuration uploads the public folder to the bucket on every deployment.

DirectoryUploadAPI referenceParent:Bucket
directoryPathRequired

Path to the local directory to upload (relative to project root).

Type: string

The bucket will mirror this directory exactly — existing files not in the directory are deleted.

fileOptions

Set HTTP headers or tags on files matching specific patterns.

Type: Array of DirectoryUploadFilter

excludeFilesPatterns

Glob patterns for files to skip during upload (relative to directoryPath).

Type: Array of string

headersPreset

Preset for HTTP caching headers, optimized for your frontend framework.

Type: string ENUM

Possible values: astro-static-websitegatsby-static-websitenuxt-static-websitesingle-page-appstatic-websitesveltekit-static-website

  • single-page-app: HTML never cached, hashed assets cached forever. For React/Vue/Angular SPAs.
  • static-website: CDN-cached, never browser-cached. For generic static sites.
  • astro-static-website / sveltekit-static-website / nuxt-static-website: Framework-specific caching (hashed build assets cached forever, HTML always fresh).

Override individual files with fileOptions.

disableS3TransferAcceleration

Disable faster uploads via S3 Transfer Acceleration. Saves a small per-GB cost.

Type: boolean

Adding metadata

You can add metadata, such as headers and tags, to the files you upload. This is useful for setting Cache-Control headers for a static website or for filtering objects in lifecycle rules.

DirectoryUploadFilterAPI referenceParent:DirectoryUpload
includePatternRequired

Glob pattern for files this rule applies to (e.g., *.html, assets/**).

Type: string

excludePattern

Glob pattern for files to exclude even if they match includePattern.

Type: string

headers

HTTP headers (e.g., Cache-Control) for matching files. Forwarded through CDN to the browser.

Type: Array of KeyValuePair

tags

Tags for matching files. Can be used to target files with lifecycleRules.

Type: Array of KeyValuePair

Encryption

If enabled, all objects uploaded to the bucket will be encrypted on the server side using the AES-256 algorithm.

resources:
  myBucket:
    type: bucket
    properties:
      encryption: true

CORS

You can configure Cross-Origin Resource Sharing (CORS) to allow web applications from other domains to access the resources in your bucket.

Custom CORS rules. First matching rule wins for each preflight request.

resources:
  myBucket:
    type: bucket
    properties:
      cors:
        enabled: true
BucketCorsConfigAPI referenceParent:Bucket
enabledRequired

Enable CORS. When true with no rules, uses permissive defaults (* origins, all methods).

Type: boolean

corsRules

Custom CORS rules. First matching rule wins for each preflight request.

Type: Array of BucketCorsRule

BucketCorsRuleAPI referenceParent:BucketCorsConfig
allowedOrigins

Allowed origins (e.g., https://example.com). Use * for any.

Type: Array of string

allowedHeaders

Allowed request headers.

Type: Array of string

allowedMethods

Allowed HTTP methods.

Type: Array of string ENUM

Possible values: *DELETEGETHEADPATCHPOSTPUT

exposedResponseHeaders

Response headers accessible to browser JavaScript.

Type: Array of string

maxAge

How long (seconds) browsers can cache preflight responses.

Type: number

Versioning

You can enable versioning to keep a complete history of all object versions. This is useful for protecting against accidental deletions or overwrites.

Keep previous versions of overwritten/deleted objects. Helps recover from mistakes.

resources:
  myBucket:
    type: bucket
    properties:
      versioning: true

CDN

You can place an AWS CloudFront CDN in front of your bucket to cache its content in edge locations around the world, reducing latency for your users. This is a common pattern for serving static websites.

For more information, see the CDN documentation.

resources:
  myBucket:
    type: bucket
    properties:
      directoryUpload:
        directoryPath: my-web/build
        headersPreset: static-website
      cdn:
        enabled: true

A bucket with a CDN and directory upload enabled.

If you're hosting a static website, consider using a hosting bucket, which is pre-configured for that use case.


Object lifecycle rules

Lifecycle rules allow you to automate the management of your objects. You can define rules to transition objects to different storage classes or delete them after a certain period.

Storage class transition

You can transition objects to a different storage class to save costs. For example, you can move infrequently accessed data to a cheaper, long-term storage class like Glacier.

  • STANDARD_IA / ONEZONE_IA: Infrequent access, instant retrieval.
  • INTELLIGENT_TIERING: AWS auto-moves between tiers based on access patterns.
  • GLACIER: Archive, minutes to hours for retrieval.
  • DEEP_ARCHIVE: Cheapest, 12+ hours for retrieval.
resources:
  myBucket:
    type: bucket
    properties:
      lifecycleRules:
        - type: class-transition
          properties:
            daysAfterUpload: 90
            storageClass: 'GLACIER'

This configuration transfers all objects to the Glacier storage class 90 days after they are uploaded.

ClassTransitionAPI referenceParent:Bucket
typeRequired
No description

Type: string "class-transition"

properties.daysAfterUploadRequired

Move objects to a cheaper storage class this many days after upload.

Type: number

properties.storageClassRequired

Target storage class. Cheaper classes have higher retrieval costs/latency.

Type: string ENUM

Possible values: DEEP_ARCHIVEGLACIERINTELLIGENT_TIERINGONEZONE_IASTANDARD_IA

  • STANDARD_IA / ONEZONE_IA: Infrequent access, instant retrieval.
  • INTELLIGENT_TIERING: AWS auto-moves between tiers based on access patterns.
  • GLACIER: Archive, minutes to hours for retrieval.
  • DEEP_ARCHIVE: Cheapest, 12+ hours for retrieval.
properties.prefix

Only apply this rule to objects with this key prefix (e.g., logs/, uploads/).

Type: string

properties.tags

Only apply this rule to objects with these tags.

Type: Array of KeyValuePair


Expiration

You can configure objects to be automatically deleted after a specified number of days.

ExpirationAPI referenceParent:Bucket
typeRequired
No description

Type: string "expiration"

properties.daysAfterUploadRequired

Delete objects this many days after upload.

Type: number

properties.prefix

Only apply this rule to objects with this key prefix (e.g., logs/, uploads/).

Type: string

properties.tags

Only apply this rule to objects with these tags.

Type: Array of KeyValuePair

resources:
  myBucket:
    type: bucket
    properties:
      lifecycleRules:
        - type: class-transition
          properties:
            daysAfterUpload: 90
            storageClass: 'GLACIER'
        - type: expiration
          properties:
            daysAfterUpload: 365

Non-current version class transition

You can transition previous versions of an object to a different storage class.

NonCurrentVersionClassTransitionAPI referenceParent:Bucket
typeRequired
No description

Type: string "non-current-version-class-transition"

properties.daysAfterVersionedRequired

Move old versions to a cheaper storage class this many days after becoming non-current.

Type: number

properties.storageClassRequired

Target storage class for non-current versions.

Type: string ENUM

Possible values: DEEP_ARCHIVEGLACIERINTELLIGENT_TIERINGONEZONE_IASTANDARD_IA

properties.prefix

Only apply this rule to objects with this key prefix (e.g., logs/, uploads/).

Type: string

properties.tags

Only apply this rule to objects with these tags.

Type: Array of KeyValuePair

resources:
  myBucket:
    type: bucket
    properties:
      versioning: true
      lifecycleRules:
        - type: non-current-version-class-transition
          properties:
            daysAfterVersioned: 10
            storageClass: 'DEEP_ARCHIVE'

Non-current version expiration

You can automatically delete previous versions of an object after a specified number of days.

NonCurrentVersionExpirationAPI referenceParent:Bucket
typeRequired
No description

Type: string "non-current-version-expiration"

properties.daysAfterVersionedRequired

Delete old versions this many days after they become non-current. Requires versioning: true.

Type: number

properties.prefix

Only apply this rule to objects with this key prefix (e.g., logs/, uploads/).

Type: string

properties.tags

Only apply this rule to objects with these tags.

Type: Array of KeyValuePair

resources:
  myBucket:
    type: bucket
    properties:
      versioning: true
      lifecycleRules:
        - type: non-current-version-expiration
          properties:
            daysAfterVersioned: 10

Abort incomplete multipart upload

You can abort multipart uploads that do not complete within a specified number of days to avoid storing incomplete object parts.

AbortIncompleteMultipartUploadAPI referenceParent:Bucket
typeRequired
No description

Type: string "abort-incomplete-multipart-upload"

properties.daysAfterInitiationRequired

Clean up incomplete multipart uploads after this many days. Prevents storage waste.

Type: number

properties.prefix

Only apply this rule to objects with this key prefix (e.g., logs/, uploads/).

Type: string

properties.tags

Only apply this rule to objects with these tags.

Type: Array of KeyValuePair

resources:
  myBucket:
    type: bucket
    properties:
      lifecycleRules:
        - type: abort-incomplete-multipart-upload
          properties:
            daysAfterInitiation: 5

Accessibility

You can control who can access your bucket and its objects.

BucketAccessibilityAPI referenceParent:Bucket
accessibilityModeDefault: privateRequired

Configures pre-defined accessibility modes for the bucket.

Type: string ENUM

Possible values: privatepublic-readpublic-read-write

This allows you to easily configure the most common access patterns.

Available modes:

  • public-read-write: Everyone can read from and write to the bucket.
  • public-read: Everyone can read from the bucket. Only compute resources and entities with sufficient IAM permissions can write to it.
  • private (default): Only compute resources and entities with sufficient IAM permissions can read from or write to the bucket.

For functions, batch jobs, and container workloads, you can grant the required IAM permissions using the allowsAccessTo or iamRoleStatements properties in their respective configurations.

accessPolicyStatements

Advanced access configuration that leverages IAM policy statements.

Type: Array of BucketPolicyIamRoleStatement

This gives you fine-grained access control over the bucket.

Accessibility modes

This allows you to easily configure the most common access patterns.

Available modes:

  • public-read-write: Everyone can read from and write to the bucket.
  • public-read: Everyone can read from the bucket. Only compute resources and entities with sufficient IAM permissions can write to it.
  • private (default): Only compute resources and entities with sufficient IAM permissions can read from or write to the bucket.

For functions, batch jobs, and container workloads, you can grant the required IAM permissions using the allowsAccessTo or iamRoleStatements properties in their respective configurations.

Access policy statements

For fine-grained control, you can define custom access policy statements. This requires knowledge of AWS IAM. For examples, see the AWS documentation.

resources:
  myBucket:
    type: bucket
    properties:
      accessibility:
        accessibilityMode: private
        accessPolicyStatements:
          - Resource:
              - $ResourceParam('myBucket', 'arn')
            Action:
              - 's3:ListBucket'
            Principal: '*'
BucketPolicyIamRoleStatementAPI referenceParent:BucketAccessibility
PrincipalRequired
No description

Type: UNSPECIFIED

ResourceRequired

ARNs of the AWS resources this statement applies to. Use "*" for all resources.

Type: Array of string

Sid

Optional identifier for this statement (for readability).

Type: string

EffectDefault: Allow

Whether to allow or deny the specified actions.

Type: string

Action

AWS actions to allow or deny (e.g., s3:GetObject, sqs:SendMessage).

Type: Array of string

Condition
No description

Type: UNSPECIFIED


Referenceable parameters

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

keyRequired

Key

Type: string

valueRequired

Value

Type: string

BucketAPI reference
typeRequired
No description

Type: string "bucket"

properties.directoryUpload

Sync a local directory to this bucket on every deploy.

Type: DirectoryUpload

Warning: Replaces all existing bucket contents. Don't use for buckets with user-uploaded or application-generated files.

properties.accessibility

Who can read/write to this bucket: private (default), public-read, or public-read-write.

Type: BucketAccessibility

properties.cors

CORS settings for browser-based access to the bucket.

Type: BucketCorsConfig

properties.versioning

Keep previous versions of overwritten/deleted objects. Helps recover from mistakes.

Type: boolean

properties.encryption

Encrypt stored objects at rest (AES-256).

Type: boolean

properties.lifecycleRules

Auto-delete or move objects to cheaper storage classes over time.

Type: Array of Expiration or NonCurrentVersionExpiration or ClassTransition or NonCurrentVersionClassTransition or AbortIncompleteMultipartUpload

Use to control storage costs: expire old files, archive infrequently accessed data, or clean up incomplete uploads.

properties.enableEventBusNotifications

Send events (object created, deleted, etc.) to EventBridge for event-driven workflows.

Type: boolean

properties.cdn

Put a CDN (CloudFront) in front of this bucket for faster downloads and lower bandwidth costs.

Type: BucketCdnConfiguration

overrides

Escape hatch to modify the underlying CloudFormation resources Stacktape creates.

Type: Object

Use dot-notation paths to override specific properties on any child resource. Find resource logical IDs with stacktape stack-info --detailed.

overrides:
  MyDbInstance:
    Properties.StorageEncrypted: true