I am working a project that sends to send SMS to the users basing on their action. The project takes advantage of Firebase Cloud Functions, Twilio and TypeScript.

You can use Node.JS with JavaScript to accomplish the project. It’s just my personal preference to do it with TypeScript.

I assume that you have Node and NPM on your computer. If you don’t, you should to to Node.js website and download it.

Before we start, you should have an Twilio account to start with. After that, you log in into the dashboard to check the Account SID and Auth Token.

Step 1: Getting started

You need to create a NPM project and install some dependencies

npm init # you know what to do

Install Twilio NPM package

// My current twilio version "^3.15.0" npm install twilio --save // ts-node package for running typescript files

npm g install ts-node

Step 2: Setting up

Create your logic to send SMS messages

// twilio.ts /**

* Typescript

* Twilio version: ^3.15.0

*/



import * as Twilio from 'twilio';



// getting ready

const twilioNumber = 'your-twilio-number';

const accountSid = 'AC-something';

const authToken = 'something-something';



const client = new Twilio(accountSid, authToken);



// start sending message



function sendText(){

const phoneNumbers = [ 'phone-number-1', 'phone-number-2']



phoneNumbers.map(phoneNumber => {

console.log(phoneNumber);



if ( !validE164(phoneNumber) ) {

throw new Error('number must be E164 format!')

}



const textContent = {

body: `You have a new sms from Dale Nguyen :)`,

to: phoneNumber,

from: twilioNumber

}



client.messages.create(textContent)

.then((message) => console.log(message.to))

})

}



// Validate E164 format

function validE164(num) {

return /^\+?[1-9]\d{1,14}$/.test(num)

}

In this code, I created a function that send messages to multiple numbers. Phone numbers is grouped in a Array named phoneNumbers. It also check for the phone number E164 format before sending out.

After configuring, you can test the sending sms function by running:

ts-node twilio.ts

* Bonus for the one who will use the function in cloud firebase functions. You should store the credential in the functions config environment.

firebase functions:config:set twilio.sid = 'abc'

firebase functions:config:set twilio.token = 'xyz'

Inside your function, you can get it by calling

const accountSid = functions.config().twilio.sid

const authToken = functions.config().twilio.token

Please check my github repository for more interesting cloud functions sippets.

https://github.com/dalenguyen/firebase-functions-snippets