The AWS CDK S3 library provides comprehensive event notification capabilities, allowing you to subscribe to S3 bucket events and route them to various AWS services including SNS topics, SQS queues, and Lambda functions. The notification system supports flexible filtering and integration with EventBridge for advanced event processing.
import { EventType, IBucketNotificationDestination, NotificationKeyFilter } from '@aws-cdk/aws-s3';
import { BucketNotificationDestinationType } from '@aws-cdk/aws-s3';All bucket instances provide methods for configuring event notifications:
interface IBucket {
addEventNotification(
event: EventType,
dest: IBucketNotificationDestination,
...filters: NotificationKeyFilter[]
): void;
addObjectCreatedNotification(
dest: IBucketNotificationDestination,
...filters: NotificationKeyFilter[]
): void;
addObjectRemovedNotification(
dest: IBucketNotificationDestination,
...filters: NotificationKeyFilter[]
): void;
}The primary method for subscribing to S3 events:
// Subscribe to any object created event
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.LambdaDestination(myLambdaFunction)
);
// Subscribe to specific event with filters
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED_PUT,
new s3n.SnsDestination(myTopic),
{ prefix: 'uploads/', suffix: '.jpg' }
);Shorthand methods for common event types:
// Equivalent to addEventNotification(EventType.OBJECT_CREATED, ...)
bucket.addObjectCreatedNotification(
new s3n.SqsDestination(myQueue),
{ prefix: 'images/' }
);
// Equivalent to addEventNotification(EventType.OBJECT_REMOVED, ...)
bucket.addObjectRemovedNotification(
new s3n.LambdaDestination(cleanupFunction),
{ suffix: '.tmp' }
);S3 supports a comprehensive set of event types for different object lifecycle stages:
enum EventType {
// Object Creation Events
OBJECT_CREATED = 's3:ObjectCreated:*',
OBJECT_CREATED_PUT = 's3:ObjectCreated:Put',
OBJECT_CREATED_POST = 's3:ObjectCreated:Post',
OBJECT_CREATED_COPY = 's3:ObjectCreated:Copy',
OBJECT_CREATED_COMPLETE_MULTIPART_UPLOAD = 's3:ObjectCreated:CompleteMultipartUpload',
// Object Removal Events
OBJECT_REMOVED = 's3:ObjectRemoved:*',
OBJECT_REMOVED_DELETE = 's3:ObjectRemoved:Delete',
OBJECT_REMOVED_DELETE_MARKER_CREATED = 's3:ObjectRemoved:DeleteMarkerCreated',
// Storage Events
REDUCED_REDUNDANCY_LOST_OBJECT = 's3:ReducedRedundancyLostObject',
// Replication Events
REPLICATION_OPERATION_FAILED_REPLICATION = 's3:Replication:OperationFailedReplication',
REPLICATION_OPERATION_MISSED_THRESHOLD = 's3:Replication:OperationMissedThreshold',
REPLICATION_OPERATION_REPLICATED_AFTER_THRESHOLD = 's3:Replication:OperationReplicatedAfterThreshold',
REPLICATION_OPERATION_NOT_TRACKED = 's3:Replication:OperationNotTracked'
}Object Creation Events: Triggered when objects are created through various APIs
OBJECT_CREATED: Wildcard matching all creation eventsOBJECT_CREATED_PUT: Direct PUT API uploadsOBJECT_CREATED_POST: Form-based POST uploadsOBJECT_CREATED_COPY: Copy operations from other S3 objectsOBJECT_CREATED_COMPLETE_MULTIPART_UPLOAD: Multipart upload completionObject Removal Events: Triggered when objects are deleted
OBJECT_REMOVED: Wildcard matching all removal eventsOBJECT_REMOVED_DELETE: Direct object deletionsOBJECT_REMOVED_DELETE_MARKER_CREATED: Versioned object delete markersStorage Events: Related to storage class changes and issues
REDUCED_REDUNDANCY_LOST_OBJECT: Reduced redundancy storage object lossReplication Events: For cross-region replication monitoring
REPLICATION_OPERATION_FAILED_REPLICATION: Replication failuresREPLICATION_OPERATION_MISSED_THRESHOLD: Replication time threshold exceededREPLICATION_OPERATION_REPLICATED_AFTER_THRESHOLD: Late replication completionREPLICATION_OPERATION_NOT_TRACKED: Objects no longer tracked by replicationS3 notifications can be sent to three types of AWS services:
interface IBucketNotificationDestination {
bind(scope: Construct, bucket: IBucket): BucketNotificationDestinationConfig;
}
interface BucketNotificationDestinationConfig {
readonly type: BucketNotificationDestinationType;
readonly arn: string;
readonly dependencies?: IDependable[];
}
enum BucketNotificationDestinationType {
LAMBDA, // AWS Lambda functions
QUEUE, // Amazon SQS queues
TOPIC // Amazon SNS topics
}Destinations are provided by the @aws-cdk/aws-s3-notifications package:
import * as s3n from '@aws-cdk/aws-s3-notifications';
// Lambda destination
const lambdaDest = new s3n.LambdaDestination(myFunction);
bucket.addEventNotification(s3.EventType.OBJECT_CREATED, lambdaDest);
// SNS topic destination
const snsDest = new s3n.SnsDestination(myTopic);
bucket.addEventNotification(s3.EventType.OBJECT_REMOVED, snsDest);
// SQS queue destination
const sqsDest = new s3n.SqsDestination(myQueue);
bucket.addEventNotification(s3.EventType.OBJECT_CREATED, sqsDest);Control which objects trigger notifications using key-based filters:
interface NotificationKeyFilter {
prefix?: string; // S3 keys must have the specified prefix
suffix?: string; // S3 keys must have the specified suffix
}// Filter by object prefix (folder-like organization)
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
destination,
{ prefix: 'uploads/' }
);
// Filter by file extension
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
destination,
{ suffix: '.jpg' }
);
// Combine prefix and suffix filters
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
destination,
{ prefix: 'images/', suffix: '.png' }
);
// Multiple filters (matches any)
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
destination,
{ prefix: 'photos/' },
{ prefix: 'videos/' }
);Filters must specify at least one of prefix or suffix. Empty filters will throw an error:
// This will throw an error
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
destination,
{ } // Invalid: must specify prefix and/or suffix
);Enable EventBridge for advanced event processing and routing:
const bucket = new s3.Bucket(this, 'MyBucket', {
eventBridgeEnabled: true // Enable EventBridge notifications
});
// EventBridge receives all S3 events automatically when enabled
// No explicit event notification setup requiredWith EventBridge enabled:
import * as s3 from '@aws-cdk/aws-s3';
import * as s3n from '@aws-cdk/aws-s3-notifications';
import * as lambda from '@aws-cdk/aws-lambda';
import * as sns from '@aws-cdk/aws-sns';
import * as sqs from '@aws-cdk/aws-sqs';
export class S3NotificationsStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string) {
super(scope, id);
const bucket = new s3.Bucket(this, 'MyBucket');
// Lambda function for image processing
const imageProcessor = new lambda.Function(this, 'ImageProcessor', {
// function configuration
});
// SNS topic for deletion alerts
const deletionTopic = new sns.Topic(this, 'DeletionAlerts');
// SQS queue for audit logging
const auditQueue = new sqs.Queue(this, 'AuditQueue');
// Process uploaded images
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.LambdaDestination(imageProcessor),
{ prefix: 'images/', suffix: '.jpg' },
{ prefix: 'images/', suffix: '.png' }
);
// Alert on file deletions
bucket.addObjectRemovedNotification(
new s3n.SnsDestination(deletionTopic)
);
// Log all bucket activity for auditing
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.SqsDestination(auditQueue)
);
bucket.addEventNotification(
s3.EventType.OBJECT_REMOVED,
new s3n.SqsDestination(auditQueue)
);
}
}