SNS subscription management provides comprehensive functionality for subscribing endpoints to topics, managing subscription attributes, handling confirmations, and listing subscriptions across various protocols.
Creates a subscription to receive messages from a topic via various protocols including email, SMS, HTTP/HTTPS, SQS, and mobile platforms.
/**
* Subscribes an endpoint to an Amazon SNS topic
* Returns a subscription ARN for confirmed subscriptions or pending confirmation
*/
class SubscribeCommand {
constructor(input: SubscribeInput);
}
interface SubscribeInput {
/** ARN of the topic to subscribe to */
TopicArn: string;
/** Protocol for message delivery */
Protocol: string;
/** Endpoint to receive messages (optional for some protocols) */
Endpoint?: string;
/** Subscription attributes for configuration */
Attributes?: SubscriptionAttributesMap;
/** Returns subscription ARN in response even if subscription is not yet confirmed */
ReturnSubscriptionArn?: boolean;
}
interface SubscribeResponse {
/** ARN of the created subscription (pending confirmation for some protocols) */
SubscriptionArn?: string;
}
interface SubscriptionAttributesMap {
[key: string]: string;
}Supported Protocols:
email - Email notificationsemail-json - Email with JSON message formatsms - SMS text messagessqs - Amazon SQS queuehttp - HTTP endpointhttps - HTTPS endpointapplication - Mobile platform applicationlambda - AWS Lambda functionfirehose - Amazon Kinesis Data FirehoseUsage Examples:
import { SNSClient, SubscribeCommand } from "@aws-sdk/client-sns";
const client = new SNSClient({ region: "us-east-1" });
// Email subscription
const emailSub = await client.send(new SubscribeCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic",
Protocol: "email",
Endpoint: "user@example.com"
}));
// SMS subscription
const smsSub = await client.send(new SubscribeCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic",
Protocol: "sms",
Endpoint: "+1234567890"
}));
// SQS subscription
const sqsSub = await client.send(new SubscribeCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic",
Protocol: "sqs",
Endpoint: "arn:aws:sqs:us-east-1:123456789012:MyQueue"
}));
// HTTP endpoint subscription
const httpSub = await client.send(new SubscribeCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic",
Protocol: "https",
Endpoint: "https://api.example.com/webhooks/sns"
}));
// Lambda function subscription
const lambdaSub = await client.send(new SubscribeCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic",
Protocol: "lambda",
Endpoint: "arn:aws:lambda:us-east-1:123456789012:function:ProcessMessage"
}));Subscription with Attributes:
const filteredSub = await client.send(new SubscribeCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic",
Protocol: "sqs",
Endpoint: "arn:aws:sqs:us-east-1:123456789012:HighPriorityQueue",
Attributes: {
FilterPolicy: JSON.stringify({
priority: ["high", "urgent"],
category: ["order", "payment"]
}),
DeliveryPolicy: JSON.stringify({
healthyRetryPolicy: {
minDelayTarget: 20,
maxDelayTarget: 20,
numRetries: 3
}
}),
RawMessageDelivery: "true"
}
}));Confirms a subscription that requires explicit confirmation (typically email and HTTP/HTTPS subscriptions).
/**
* Confirms a subscription to an Amazon SNS topic
* Required for email and HTTP/HTTPS protocol subscriptions
*/
class ConfirmSubscriptionCommand {
constructor(input: ConfirmSubscriptionInput);
}
interface ConfirmSubscriptionInput {
/** ARN of the topic */
TopicArn: string;
/** Confirmation token received via the subscription endpoint */
Token: string;
/** Whether to authenticate unsubscribe requests */
AuthenticateOnUnsubscribe?: string;
}
interface ConfirmSubscriptionResponse {
/** ARN of the confirmed subscription */
SubscriptionArn?: string;
}Usage Example:
// Typically called from a confirmation endpoint or email click
const confirmed = await client.send(new ConfirmSubscriptionCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic",
Token: "subscription-confirmation-token-from-message",
AuthenticateOnUnsubscribe: "true"
}));
console.log("Subscription confirmed:", confirmed.SubscriptionArn);Removes a subscription from a topic.
/**
* Deletes a subscription from an Amazon SNS topic
* Stops message delivery to the subscribed endpoint
*/
class UnsubscribeCommand {
constructor(input: UnsubscribeInput);
}
interface UnsubscribeInput {
/** ARN of the subscription to delete */
SubscriptionArn: string;
}Usage Example:
await client.send(new UnsubscribeCommand({
SubscriptionArn: "arn:aws:sns:us-east-1:123456789012:MyTopic:subscription-id"
}));Retrieves attributes and configuration for a specific subscription.
/**
* Returns subscription attributes including delivery configuration and statistics
*/
class GetSubscriptionAttributesCommand {
constructor(input: GetSubscriptionAttributesInput);
}
interface GetSubscriptionAttributesInput {
/** ARN of the subscription */
SubscriptionArn: string;
}
interface GetSubscriptionAttributesResponse {
/** Map of attribute names to values */
Attributes?: SubscriptionAttributesMap;
}Common Subscription Attributes:
SubscriptionArn: The subscription's ARNTopicArn: ARN of the subscribed topicOwner: AWS account ID of the subscription ownerProtocol: Message delivery protocolEndpoint: Delivery endpointConfirmationWasAuthenticated: Whether confirmation was authenticatedDeliveryPolicy: JSON delivery retry policyEffectiveDeliveryPolicy: Currently active delivery policyFilterPolicy: JSON message filtering policyPendingConfirmation: Whether subscription is pending confirmationRawMessageDelivery: Whether raw message delivery is enabledRedrivePolicy: Dead letter queue configurationUsage Example:
const attributes = await client.send(new GetSubscriptionAttributesCommand({
SubscriptionArn: "arn:aws:sns:us-east-1:123456789012:MyTopic:subscription-id"
}));
console.log("Protocol:", attributes.Attributes?.Protocol);
console.log("Endpoint:", attributes.Attributes?.Endpoint);
console.log("Filter Policy:", attributes.Attributes?.FilterPolicy);Modifies attributes for an existing subscription.
/**
* Sets an attribute for a subscription
* Allows modification of delivery and filtering configuration
*/
class SetSubscriptionAttributesCommand {
constructor(input: SetSubscriptionAttributesInput);
}
interface SetSubscriptionAttributesInput {
/** ARN of the subscription */
SubscriptionArn: string;
/** Name of the attribute to set */
AttributeName: string;
/** Value of the attribute */
AttributeValue?: string;
}Usage Examples:
// Set message filtering policy
await client.send(new SetSubscriptionAttributesCommand({
SubscriptionArn: "arn:aws:sns:us-east-1:123456789012:MyTopic:subscription-id",
AttributeName: "FilterPolicy",
AttributeValue: JSON.stringify({
priority: ["high", "medium"],
region: ["us-east-1", "us-west-2"]
})
}));
// Enable raw message delivery for SQS
await client.send(new SetSubscriptionAttributesCommand({
SubscriptionArn: "arn:aws:sns:us-east-1:123456789012:MyTopic:subscription-id",
AttributeName: "RawMessageDelivery",
AttributeValue: "true"
}));
// Set delivery policy
await client.send(new SetSubscriptionAttributesCommand({
SubscriptionArn: "arn:aws:sns:us-east-1:123456789012:MyTopic:subscription-id",
AttributeName: "DeliveryPolicy",
AttributeValue: JSON.stringify({
healthyRetryPolicy: {
minDelayTarget: 20,
maxDelayTarget: 20,
numRetries: 3
},
sicklyRetryPolicy: {
minDelayTarget: 20,
maxDelayTarget: 20,
numRetries: 3
},
throttlePolicy: {
maxReceivesPerMinute: 100
}
})
}));
// Set dead letter queue
await client.send(new SetSubscriptionAttributesCommand({
SubscriptionArn: "arn:aws:sns:us-east-1:123456789012:MyTopic:subscription-id",
AttributeName: "RedrivePolicy",
AttributeValue: JSON.stringify({
deadLetterTargetArn: "arn:aws:sqs:us-east-1:123456789012:MyDLQ"
})
}));Lists all subscriptions in the account with pagination support.
/**
* Returns a list of all subscriptions in the account
* Supports pagination for large numbers of subscriptions
*/
class ListSubscriptionsCommand {
constructor(input?: ListSubscriptionsInput);
}
interface ListSubscriptionsInput {
/** Pagination token from previous request */
NextToken?: string;
}
interface ListSubscriptionsResponse {
/** Array of subscription information */
Subscriptions?: Subscription[];
/** Token for next page of results */
NextToken?: string;
}
interface Subscription {
/** ARN of the subscription */
SubscriptionArn?: string;
/** AWS account ID that owns the subscription */
Owner?: string;
/** Message delivery protocol */
Protocol?: string;
/** Delivery endpoint */
Endpoint?: string;
/** ARN of the subscribed topic */
TopicArn?: string;
}Usage Example:
// List all subscriptions
const subscriptions = await client.send(new ListSubscriptionsCommand());
subscriptions.Subscriptions?.forEach(sub => {
console.log(`${sub.Protocol}: ${sub.Endpoint} -> ${sub.TopicArn}`);
});
// Paginate through all subscriptions
let nextToken: string | undefined;
do {
const result = await client.send(new ListSubscriptionsCommand({
NextToken: nextToken
}));
result.Subscriptions?.forEach(subscription => {
console.log("Subscription:", subscription.SubscriptionArn);
console.log("Protocol:", subscription.Protocol);
console.log("Endpoint:", subscription.Endpoint);
});
nextToken = result.NextToken;
} while (nextToken);Lists all subscriptions for a specific topic.
/**
* Returns a list of subscriptions for a specific topic
* Useful for topic-specific subscription management
*/
class ListSubscriptionsByTopicCommand {
constructor(input: ListSubscriptionsByTopicInput);
}
interface ListSubscriptionsByTopicInput {
/** ARN of the topic */
TopicArn: string;
/** Pagination token from previous request */
NextToken?: string;
}
interface ListSubscriptionsByTopicResponse {
/** Array of subscription information for the topic */
Subscriptions?: Subscription[];
/** Token for next page of results */
NextToken?: string;
}Usage Example:
const topicSubscriptions = await client.send(new ListSubscriptionsByTopicCommand({
TopicArn: "arn:aws:sns:us-east-1:123456789012:MyTopic"
}));
topicSubscriptions.Subscriptions?.forEach(sub => {
console.log(`${sub.Protocol} subscription: ${sub.Endpoint}`);
});Message filtering allows subscriptions to receive only messages that match specific criteria.
interface FilterPolicy {
[attributeName: string]:
| string
| number
| boolean
| string[]
| number[]
| FilterPolicyCondition;
}
interface FilterPolicyCondition {
/** Anything-but filter */
'anything-but'?: string | number | (string | number)[];
/** Numeric range filter */
numeric?: Array<'=' | '>' | '>=' | '<' | '<=' | string | number>;
/** Exists filter */
exists?: boolean;
/** Prefix filter */
prefix?: string;
}Filter Policy Examples:
// Simple attribute matching
const simpleFilter = {
priority: ["high", "urgent"],
category: "order"
};
// Numeric range filtering
const numericFilter = {
price: { numeric: [">=", 100, "<=", 1000] },
quantity: { numeric: [">", 0] }
};
// Complex conditions
const complexFilter = {
region: { "anything-but": ["us-west-1"] },
hasDiscount: { exists: true },
customerType: { prefix: "premium" },
orderValue: { numeric: [">=", 50] }
};Configure retry behavior and throttling for message delivery.
interface DeliveryPolicy {
healthyRetryPolicy?: {
minDelayTarget?: number;
maxDelayTarget?: number;
numRetries?: number;
numMaxDelayRetries?: number;
numMinDelayRetries?: number;
numNoDelayRetries?: number;
backoffFunction?: 'linear' | 'arithmetic' | 'geometric' | 'exponential';
};
sicklyRetryPolicy?: {
minDelayTarget?: number;
maxDelayTarget?: number;
numRetries?: number;
numMaxDelayRetries?: number;
numMinDelayRetries?: number;
numNoDelayRetries?: number;
backoffFunction?: 'linear' | 'arithmetic' | 'geometric' | 'exponential';
};
throttlePolicy?: {
maxReceivesPerMinute?: number;
};
requestPolicy?: {
headerContentType?: string;
};
}Configure dead letter queues for failed message deliveries.
interface RedrivePolicy {
deadLetterTargetArn: string;
}Multi-Protocol Notification:
const topicArn = "arn:aws:sns:us-east-1:123456789012:Notifications";
// Subscribe multiple endpoints to same topic
const subscriptions = await Promise.all([
// Email notification
client.send(new SubscribeCommand({
TopicArn: topicArn,
Protocol: "email",
Endpoint: "admin@example.com"
})),
// SMS for urgent notifications
client.send(new SubscribeCommand({
TopicArn: topicArn,
Protocol: "sms",
Endpoint: "+1234567890",
Attributes: {
FilterPolicy: JSON.stringify({ priority: "urgent" })
}
})),
// SQS for processing
client.send(new SubscribeCommand({
TopicArn: topicArn,
Protocol: "sqs",
Endpoint: "arn:aws:sqs:us-east-1:123456789012:ProcessingQueue",
Attributes: {
RawMessageDelivery: "true"
}
})),
// Webhook for external systems
client.send(new SubscribeCommand({
TopicArn: topicArn,
Protocol: "https",
Endpoint: "https://api.external.com/webhooks/sns"
}))
]);Subscription Cleanup:
const cleanupSubscriptions = async (topicArn: string) => {
const subscriptions = await client.send(new ListSubscriptionsByTopicCommand({
TopicArn: topicArn
}));
for (const subscription of subscriptions.Subscriptions || []) {
if (subscription.SubscriptionArn &&
subscription.SubscriptionArn !== "PendingConfirmation") {
await client.send(new UnsubscribeCommand({
SubscriptionArn: subscription.SubscriptionArn
}));
console.log(`Unsubscribed: ${subscription.SubscriptionArn}`);
}
}
};