# Topic

A new SNS topic.

Extends: Construct › Resource › TopicBase › Topic
Implements: IResource, INotificationRuleTarget, IEncryptedResource, ITopic, IEnvironmentAware, ITopicRef, IConstruct, IDependable

- CloudFormation: [`AWS::SNS::Topic`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-sns-topic.html)
- L1 type: [`CfnTopic`](/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.274.0/packages/aws-cdk-lib/aws-sns/lib/topic.ts#L248)
- Type last changed: v2.196.0 · 16 May 2025

## Example

```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
    }),
  ],
});
```

## Initializer

```ts
new Topic(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](/cdk/api/v2/docs/aws-cdk-lib.aws_sns.FifoThroughputScope.html) = undefined - SNS default setting is FifoThroughputScope.TOPIC — Specifies the throughput quota and deduplication behavior to apply for the FIFO topic.

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

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

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

- `masterKey`: [IKey](/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 = do not archive messages — The number of days Amazon SNS retains 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 = Generated name — A name for the topic.

  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](/cdk/api/v2/docs/aws-cdk-lib.aws_sns.TracingConfig.html) = TracingConfig.PASS_THROUGH — Tracing mode of an Amazon SNS topic.

## Properties

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

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) (required) — 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 (required) — Whether this topic is an Amazon SNS FIFO queue.

  If false, this is a standard topic.

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

- `masterKey`: [IKey](/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](/cdk/api/v2/docs/constructs.Node.html) (required) — The tree node.

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

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

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

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

- `topicRef`: [TopicReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_sns.TopicReference.html) (required) — 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.

- `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.

  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.

  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.
