Simple Notification Service with NextJs

Last Updated April 08, 2024

Step:1 Open Management Console and Log back in.

Step:2 Open services, type SNS and open it.

Step3: Create New Topic (Test SNS)

Step:4 Topic TestSNS created Successfully.

Step:5

Click on Create subscription and Create

Click on protocol what you want then create subscription.(EMAIL)

Step:6 Then confirm your Email…

Step:7 Subscription Confirmed

Step:8

You can also Check the subscription in Management Console  ( SNS ->Topics -> TestSNS)

Step:9 After Subscription is Confirmed Write an API to SNS to Send the E-MAIL.


import { SNSClient, PublishCommandInput, PublishCommand } from '@aws-sdk/client-sns';
import { NextRequest, NextResponse } from "next/server";
require('dotenv').config();

interface SendEmailsRequest {
  message: string;
  subject?: string;
}

export  async function POST(req: NextRequest) {
  try {
    if (req.method !== 'POST') {
      return NextResponse.json({ error: 'Method Not Allowed' });
    }

    const emailBody: SendEmailsRequest = await req.json();

    console.log(emailBody);

    const sns = new SNSClient({
        region: process.env.AWS_REGION as string,
        credentials: {
          accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
          secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
        }
      });
      

    const results: any[] = [];
    
      try {
        const params: PublishCommandInput = {
          Message: emailBody.message,
          Subject: emailBody.subject,
          TopicArn: process.env.EMAIL_TOPIC_ARN, // Replace with your email topic ARN
          MessageAttributes: {
            // Add any required message attributes for email, e.g., { 'EmailMessage.Destination': { ... } }
          },
          MessageStructure: 'string', // Use 'json' if sending a structured message
        };

        const result = await sns.send( new  PublishCommand(params)); 
        results.push(result);
      } catch (error) {
        console.error(`Error sending email`, error);
        
      }
    

   return NextResponse.json({ success: true, results });
  } catch (error) {
    console.error('General error:', error);
    return NextResponse.json({ error: 'Failed to send emails' });
  }
}

Step:10 To Test the API open Postman and type the URL of API



Step:11

Choose Post Method and Type Attributes in JSON Format and click on send.

In the Terminal you can see Success: true

Step:12

You Can See the E-MAIL that you got message from AWS Notifications

Coporate & Communication Address:

Bangalore Office Location: Yelahanka New Town, Bangalore

Nagpur Office Location: NANDANVAN, Nagpur-440009

Important Links

PricingProjects

Copyright © 2024. Powered by Moss Tech.