Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

How to Send SMS with Twilio in Node.js

cloud & nodejs tutorials
Dev Genius
Published in
3 min readFeb 26, 2024

Introduction

Integrating SMS functionality into your Node.js application can significantly enhance user interaction by providing instant notifications, security alerts, or two-factor authentication. Twilio’s powerful API simplifies the process of sending SMS messages. This guide will walk you through how to send SMS messages with Twilio in Node.js, including the necessary steps to write comprehensive unit tests.

Prerequisites

  • Twilio Account: Sign up at Twilio and obtain your Account SID, Auth Token, and a Twilio phone number capable of sending SMS.
  • Node.js: Ensure Node.js is installed on your machine. Download Node.js.
  • Environment for Development: A code editor and terminal for executing commands.

Step 1: Setting Up Your Node.js Project

Create a new directory for your project and navigate into it:

mkdir twilio-sms-node
cd twilio-sms-node

Initialize your Node.js project:

npm init -y

Install the Twilio Node.js SDK:

npm install twilio

Step 2: Implementing the SMS Sending Function

Create a file named sendSms.js in your project directory. Add the following code, which uses the Twilio SDK to send an SMS message:

require('dotenv').config();
const twilio = require('twilio');

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function sendSms(to, body) {
try {
const message = await client.messages.create({
body,
from: process.env.TWILIO_PHONE_NUMBER,
to,
});
console.log(`Message sent: ${message.sid}`);
return message.sid;
} catch (error) {
console.error(`Failed to send SMS: ${error}`);
throw error;
}
}

module.exports = sendSms;

Ensure your Twilio Account SID, Auth Token, and phone number are stored securely, preferably in environment variables.

Step 3: Unit Testing with Jest

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response