Skip to content
GitHub Discord

Subscribe to topics

Create an SNS topic, publish to it from a function, and subscribe to it with a function and a queue.

sst.config.ts
const queue = new sst.aws.Queue("MyQueue");
queue.subscribe("subscriber.handler");
const topic = new sst.aws.SnsTopic("MyTopic");
topic.subscribe("MySubscriber1", "subscriber.handler", {});
topic.subscribeQueue("MySubscriber2", queue.arn);
const app = new sst.aws.Function("MyApp", {
handler: "publisher.handler",
link: [topic],
url: true,
});
subscriber.ts
import type { SQSEvent } from "aws-lambda";
export const handler = async (event: SQSEvent) => {
console.log(event);
return "ok";
};
publisher.ts
import { Resource } from "sst";
import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";
const client = new SNSClient();
export const handler = async (event) => {
await client.send(
new PublishCommand({
TargetArn: Resource.MyTopic.arn,
Message: JSON.stringify({ foo: "bar" }),
MessageAttributes: { foo: { DataType: "String", StringValue: "bar" } },
})
);
return {
statusCode: 200,
body: JSON.stringify({ status: "sent" }, null, 2),
};
};

View the full example.