Send SMS – Twilio via Nodejs
Hello. In this tutorial, we will create a simple nodejs application for sending SMS with Twilio.
1. Introduction
Sending SMS these days is handy as it is useful across various business use cases. For sending SMS via this nodejs application I will be using Twilio under a free tier account which offers limited support but should be good for our implementation. I already have a Twilio free-tier account that I will be using for this tutorial.
1.1 Setting up Node.js
To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.
2. Send message from Twilio via Nodejs
To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE. Let a take a quick peek at the project structure.
2.1 Setting up related dependencies
2.1.1 Setting up project packages
Navigate to the project directory and run npm init -y
to create a package.json
file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Replace the generated file with the code given below –
package.json
{ "name": "nodejs-twilio", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "nodemon index.js", "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "config": "^3.3.7", "express": "^4.18.1", "twilio": "^3.80.0" }, "devDependencies": { "nodemon": "^2.0.19" } }
Once the file is replaced trigger the below npm
command in the terminal window to download the different packages required for this tutorial. The downloaded packages will reside inside the node_modules
folder.
Downloading dependencies
npm install
2.2 Setting up code files
2.2.1 Setting up the configuration file
Create a configuration file in the config
folder that will hold the Twilio and application details. The Twilio details such as account id, authentication token, and phone number can be obtained from the first project created under the free-tier account.
default.json
{ "app": { "dev": { "port": 3301, "host": "localhost" } }, "twilio": { "dev": { "account_sid": "TWILIO_ACCOUNT_SID", "auth_token": "TWILIO_AUTHENTICATION_TOKEN", "phone_number": "TWILIO_PHONE_NUMBER" } } }
2.2.2 Creating a router implementation
Create a route file responsible to handle the incoming requests from the client. The file will expose 2 endpoints and will be created in the src/api
folder inside the project’s root directory.
/api
: HTTP GET endpoint to get the application status/api/sms
: HTTP POST endpoint to send the SMS via Twilio api
routes.js
// packages. const config = require("config"); const express = require("express"); const router = express.Router(); // setup twilio account const client = require("twilio")( config.get("twilio.dev.account_sid"), config.get("twilio.dev.auth_token"), { logLevel: "debug" } ); // application endpoints. /* -- health -- http get http://localhost:3301/api */ router.get("/", (req, res) => { return res.status(200).json({ status: "up", info: "application is healthy" }); }); /* -- send an SMS message -- http post http://localhost:3301/api/sms -- request body { "to": "PHONE_NUMBER_WITH_PLUS_SYMBOL_AND_COUNTRY_CODE", "message": "RANDOM_TEXT" } */ router.post("/sms", (req, res) => { // todo - add logic to validate recipient number as per country. sendSms(req, res); }); // helper method function sendSms(req, res) { client.messages .create({ body: req.body.message, to: req.body.to, from: config.get("twilio.dev.phone_number") }) .then((message) => { // console.log(message); return res .status(202) .json({ status: message.status, info: message.sid }); }) .catch((err) => { // console.log(error); return res.status(500).json({ status: "some error occurred", info: err }); }); } module.exports = router;
2.2.3 Create an implementation file
Create an implementation file in the project’s root directory responsible to handle the application startup and forwarding the incoming requests to the router methods.
index.js
// packages. const config = require("config"); const express = require("express"); const app = express(); app.use(express.json()); // application routes. app.use("/api", require("./src/api/routes")); // driver code. const host = config.get("app.dev.host"); const port = config.get("app.dev.port"); app.listen(port, () => { console.log(`App available at http://${host}:${port}`); });
3. Run the setup
To run the application navigate to the project directory and enter the following command as shown below in the terminal. The application will be started successfully on the port number – 3301
.
Run command
$ npm run start
Once the application is started successfully the logger message – “App available at http://localhost:3301” will be shown on the terminal window.
4. Demo
The application exposes the below endpoints that you can explore around the application with the help of the postman tool. Once you hit the /api/sms
endpoint the Twilio api would be triggered based on the configuration and will send an SMS to the recipient’s phone number.
Application endpoints
/* -- health -- http get http://localhost:3301/api */ /* -- send an SMS message -- http post http://localhost:3301/api/sms -- request body { "to": "PHONE_NUMBER_WITH_PLUS_SYMBOL_AND_COUNTRY_CODE", "message": "RANDOM_TEXT" } */
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
5. Summary
In this tutorial, we created a nodejs application and integrated it with Twilio to enable the SMS feature in the application. You can download the source code from the Downloads section.
6. Download the Project
This was a tutorial to integrate the Twilio SMS feature with the nodejs application.
You can download the full source code of this example here: Send message from Twilio via Nodejs