# Topic

A new SNS topic.

Extends: [Construct](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html) › [Resource](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Resource.html) › [TopicBase](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sns.TopicBase.html) › Topic
Implements: [IResource](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IResource.html), [INotificationRuleTarget](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codestarnotifications.INotificationRuleTarget.html), [IEncryptedResource](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IEncryptedResource.html), [ITopic](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sns.ITopic.html), IEnvironmentAware, ITopicRef, IConstruct, IDependable

- CloudFormation: [`AWS::SNS::Topic`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-sns-topic.html)
- L1 type: [`CfnTopic`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sns.CfnTopic.html)
- Source: [`aws-sns/lib/topic.ts`](https://github.com/aws/aws-cdk/blob/v2.277.0/packages/aws-cdk-lib/aws-sns/lib/topic.ts#L248)
- Type last changed: v2.196.0 · 16 May 2025

## Example

TypeScript:

```ts
import * as sns from 'aws-cdk-lib/aws-sns';

const topic = new sns.Topic(this, 'MyTopic');

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'",
  ),
  actions: [
    new actions.SnsTopicAction(topic, {
      messageFormat: actions.SnsActionMessageFormat.JSON, // optional property, default is SnsActionMessageFormat.RAW
    }),
  ],
});
```

Python:

```python
import aws_cdk.aws_sns as sns

topic = sns.Topic(self, "MyTopic")

topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    actions=[
        actions.SnsTopicAction(topic,
            message_format=actions.SnsActionMessageFormat.JSON
        )
    ]
)
```

Java:

```java
import software.amazon.awscdk.services.sns.*;

Topic topic = new Topic(this, "MyTopic");

TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"))
        .actions(List.of(
            SnsTopicAction.Builder.create(topic)
                    .messageFormat(SnsActionMessageFormat.JSON)
                    .build()))
        .build();
```

C# / .NET:

```csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.SNS;

var topic = new Topic(this, "MyTopic");

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    Actions = new [] {
        new SnsTopicAction(topic, new SnsTopicActionProps {
            MessageFormat = SnsActionMessageFormat.JSON
        }) }
});
```

Golang:

```go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import sns "github.com/aws/aws-cdk-go/awscdk"

topic := sns.NewTopic(this, jsii.String("MyTopic"))

topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewSnsTopicAction(topic, &SnsTopicActionProps{
			MessageFormat: actions.SnsActionMessageFormat_JSON,
		}),
	},
})
```

## Initializer

TypeScript:

```ts
new Topic(scope: Construct, id: string, props?: TopicProps)
```

Python:

```python
Topic(scope: Construct, id: str, props: typing.Optional[TopicProps] = None)
```

Java:

```java
new Topic(Construct scope, String id, TopicProps props)
```

C# / .NET:

```csharp
new Topic(Construct scope, string id, TopicProps? props = null)
```

Golang:

```go
NewTopic(Scope Construct, Id *string, Props TopicProps)
```

## Construct Props

- `contentBasedDeduplication`: boolean = None — Enables content-based deduplication for FIFO topics.

- `displayName`: string = None — A developer-defined string that can be used to identify this SNS topic.

  The display name must be maximum 100 characters long, including hyphens (-),
  underscores (_), spaces, and tabs.

- `enforceSSL`: boolean = false — Adds a statement to enforce encryption of data in transit when publishing to the topic.

- `fifo`: boolean = None — Set to true to create a FIFO topic.

- `fifoThroughputScope`: [FifoThroughputScope](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sns.FifoThroughputScope.html) — Specifies the throughput quota and deduplication behavior to apply for the FIFO topic.

  **Default:** undefined - SNS default setting is FifoThroughputScope.TOPIC

  You can only set this property when `fifo` is `true`.

- `loggingConfigs`: [LoggingConfig](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sns.LoggingConfig.html)[] = None — The list of delivery status logging configurations for the topic.

- `masterKey`: [IKey](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_kms.IKey.html) = None — A KMS Key, either managed by this CDK app, or imported.

- `messageRetentionPeriodInDays`: number — The number of days Amazon SNS retains messages.

  **Default:** do not archive messages

  It can only be set for FIFO topics.

- `signatureVersion`: string = 1 — The signature version corresponds to the hashing algorithm used while creating the signature of the notifications, subscription confirmations, or unsubscribe confirmation messages sent by Amazon SNS.

- `topicName`: string — A name for the topic.

  **Default:** Generated name

  If you don't specify a name, AWS CloudFormation generates a unique
  physical ID and uses that ID for the topic name. For more information,
  see Name Type.

- `tracingConfig`: [TracingConfig](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sns.TracingConfig.html) = TracingConfig.PASS_THROUGH — Tracing mode of an Amazon SNS topic.

## Properties

- `contentBasedDeduplication`: boolean — Enables content-based deduplication for FIFO topics.

- `env`: [ResourceEnvironment](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) — The environment this resource belongs to.

  For resources that are created and managed in a Stack (those created by
  creating new class instances like `new Role()`, `new Bucket()`, etc.), this
  is always the same as the environment of the stack they belong to.

  For referenced resources (those obtained from referencing methods like
  `Role.fromRoleArn()`, `Bucket.fromBucketName()`, etc.), they might be
  different than the stack they were imported into.

- `fifo`: boolean — Whether this topic is an Amazon SNS FIFO queue.

  If false, this is a standard topic.

- `grants`: [TopicGrants](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_sns.TopicGrants.html) — Collection of grant methods for a Topic.

- `masterKey`: [IKey](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_kms.IKey.html) — A KMS Key, either managed by this CDK app, or imported.

  This property applies only to server-side encryption.

- `node`: [Node](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html) — The tree node.

- `PROPERTY_INJECTION_ID`: string (static) — Uniquely identifies this class.

- `stack`: [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) — The stack in which this resource is defined.

- `topicArn`: string — The ARN of the topic.

- `topicName`: string — The name of the topic.

- `topicRef`: [TopicReference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_sns.TopicReference.html) — A reference to a Topic resource.

## Methods

- `addLoggingConfig(config: LoggingConfig): void` — Adds a delivery status logging configuration to the topic.

- `addSubscription(topicSubscription: ITopicSubscription): Subscription` — Subscribe some endpoint to this topic.

  Creates an `AWS::SNS::Subscription` resource. The endpoint and protocol
  come from the given `ITopicSubscription` (for example an SQS queue, a
  Lambda function or an email address). For some subscribers the
  subscription also waits for a related resource; for example, an SQS
  subscription is created only after the queue policy that lets the topic
  send to the queue.

  Subscribing the same subscriber to this topic twice throws an error.

- `addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResult` — Adds a statement to the IAM resource policy associated with this topic.

  If this topic was created in this stack (`new Topic`), a topic policy
  will be automatically created upon the first call to `addToResourcePolicy`.
  However, if `enforceSSL` is set to `true`, the policy has already been created
  before the first call to this method.

  If the topic is imported (`Topic.import`), then this is a no-op.

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  When set, any cross-stack reference to this resource will use the specified
  mechanism instead of the global default determined by the
  `@aws-cdk/core:defaultCrossStackReferences` context key. This is useful for
  selectively weakening specific references to avoid the "deadly embrace" problem
  without changing the app-wide default.

  **Parameters**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — Apply the given removal policy to this resource.

  The Removal Policy controls what happens to this resource when it stops
  being managed by CloudFormation, either because you've removed it from the
  CDK application or because you've made a change that requires the resource
  to be replaced.

  The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
  account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).

- `bindAsNotificationRuleTarget(_scope: Construct): NotificationRuleTargetConfig` — Represents a notification target That allows SNS topic to associate with this rule target.

- `fromTopicArn(scope: Construct, id: string, topicArn: string): ITopic` (static) — Import an existing SNS topic provided an ARN.

  **Parameters**

  - `scope` — The parent creating construct.
  - `id` — The construct's name.
  - `topicArn` — topic ARN (i.e. arn:aws:sns:us-east-2:444455556666:MyTopic).

- `fromTopicAttributes(scope: Construct, id: string, attrs: TopicAttributes): ITopic` (static) — Import an existing SNS topic provided a topic attributes.

  **Parameters**

  - `scope` — The parent creating construct.
  - `id` — The construct's name.
  - `attrs` — the attributes of the topic to import.

- `grantOnKey(grantee: IGrantable, ...actions: string[]): GrantOnKeyResult` — Gives permissions to a grantable entity to perform actions on the encryption key.

- `grantPublish(grantee: IGrantable): Grant` — Grant topic publishing permissions to the given identity.

  This will grant the following permissions:

   - sns:Publish

  If the topic is encrypted with a customer-managed KMS key, permission
  to use the key for encryption will also be granted to the same principal.

  This will grant the following KMS permissions:

   - kms:Decrypt
   - kms:GenerateDataKey*

  The use of this method is discouraged. Please use `grants.publish()` instead.

  [disable-awslint:no-grants]

- `grantSubscribe(grantee: IGrantable): Grant` — Grant topic subscribing permissions to the given identity.

  This will grant the following permissions:

   - sns:Subscribe

  Note that this only grants permission to call the `Subscribe` API;
  it does not grant permission to receive messages on a particular
  delivery protocol. KMS permissions are not required because subscribing
  does not access topic message payloads.

  The use of this method is discouraged. Please use `grants.subscribe()` instead.

  [disable-awslint:no-grants]

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  Use this method instead of `instanceof` to properly detect `Construct`
  instances, even when the construct library is symlinked.

  Explanation: in JavaScript, multiple copies of the `constructs` library on
  disk are seen as independent, completely different libraries. As a
  consequence, the class `Construct` in each copy of the `constructs` library
  is seen as a different class, and an instance of one class will not test as
  `instanceof` the other class. `npm install` will not create installations
  like this, but users may manually symlink construct libraries together or
  use a monorepo tool: in those cases, multiple copies of the `constructs`
  library can be accidentally installed, and `instanceof` will behave
  unpredictably. It is safest to avoid using `instanceof`, and using
  this type-testing method instead.

  **Parameters**

  - `x` — Any object.

  **Returns:** true if `x` is an object created from a class which extends `Construct`.

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `metric(metricName: string, props?: MetricOptions): Metric` — Return the given named metric for this Topic.

- `metricNumberOfMessagesPublished(props?: MetricOptions): Metric` — The number of messages published to your Amazon SNS topics.

  Sum over 5 minutes

- `metricNumberOfNotificationsDelivered(props?: MetricOptions): Metric` — The number of messages successfully delivered from your Amazon SNS topics to subscribing endpoints.

  Sum over 5 minutes

- `metricNumberOfNotificationsFailed(props?: MetricOptions): Metric` — The number of messages that Amazon SNS failed to deliver.

  Sum over 5 minutes

- `metricNumberOfNotificationsFilteredOut(props?: MetricOptions): Metric` — The number of messages that were rejected by subscription filter policies.

  Sum over 5 minutes

- `metricNumberOfNotificationsFilteredOutInvalidAttributes(props?: MetricOptions): Metric` — The number of messages that were rejected by subscription filter policies because the messages' attributes are invalid.

  Sum over 5 minutes

- `metricNumberOfNotificationsFilteredOutNoMessageAttributes(props?: MetricOptions): Metric` — The number of messages that were rejected by subscription filter policies because the messages have no attributes.

  Sum over 5 minutes

- `metricPublishSize(props?: MetricOptions): Metric` — Metric for the size of messages published through this topic.

  Average over 5 minutes

- `metricSMSMonthToDateSpentUSD(props?: MetricOptions): Metric` — The charges you have accrued since the start of the current calendar month for sending SMS messages.

  Maximum over 5 minutes

- `metricSMSSuccessRate(props?: MetricOptions): Metric` — The rate of successful SMS message deliveries.

  Sum over 5 minutes

- `toString(): string` — Returns a string representation of this construct.

- `with(...mixins: IMixin[]): IConstruct` — Applies one or more mixins to this construct.

  Mixins are applied in order. The list of constructs is captured at the
  start of the call, so constructs added by a mixin will not be visited.
  Use multiple `with()` calls if subsequent mixins should apply to added
  constructs.
