How to Send SMS using NodeJS and Google Cloud Functions

card image
February 21, 2024
Written by
Reviewed by

How to Send SMS using NodeJS and Google Cloud Functions

In today's high-speed, interconnected world, the ability to communicate quickly and effectively is paramount. Over the past couple of decades, SMS and messaging apps like WhatsApp have revolutionized the way businesses connect with their customers. They are significant tools for modern-day communication, and harnessing their power could add significant value to your business.

Understanding how to leverage such tools is an essential coding skill in our tech-driven world. This post will guide you on how to send SMS with Node.js using Google Cloud Functions , a light-weight, event-based, asynchronous compute solution that allows you to create small, single-purpose functions that respond to cloud events without the need to manage a server or a runtime environment.

Typically, Twilio Functions serve as a great platform for serverless tasks involving SMS. This purpose-built environment is tailored to build and run code that interacts with Twilio’s communications platform. However, specific project requirements or constraints might necessitate the use of other runtimes, like Google Cloud Functions. This post demonstrates that you have powerful options outside Twilio's sphere. Remember, your best tech choice always aligns with your specific needs!

Prerequisites

You need to ensure you have the following before moving forward:

Using Google Cloud Functions to send SMS

By following these steps, you can create your own SMS sending service using Google Cloud Functions. Just imagine all the value and convenience that it puts in your hands.

Leveraging the robust features of Google Cloud Functions to communicate quickly, effectively and efficiently.

Copy your Twilio Credentials

Once you are logged in to the Twilio Console , scroll down to find your Account SID and Auth Token. Copy these values, as you’ll need them later.

Twilio Console showing the auth token

Purchase the phone number you want to use

To send a message, you need to buy a phone number—ideally from the region you are based in—to avoid roaming charges. To accomplish this, go to the Twilio Console and search for a number you’d like to buy.

Twilio Console to purchase a number

Also copy this number for later usage.

Regulators all over the world try to fight SMS fraud by implementing certain guidelines and restrictions on the purchase of phone numbers. So there might be some additional steps required for your country. Here’s a list of all regulatory guidelines .

Use the Power of Google Cloud Functions

Google Cloud Functions act as building blocks for serverless applications and allow you to run your code without provisioning or managing servers.

Go to the GCP Console to create a new Cloud Function. Click the blue Create Function button.

GCP console to create a new function
You possibly need to enable the proper API in a modal dialog. If you see this one, confirm with Enable.

In the next form, give the new function a name like send-sms. For this demo, we’re happy with an HTTPS-based trigger. Only authenticated requests should be able to trigger the function and, hence, send text messages. Make sure to choose Require Authentication. If you have a larger footprint on GCP, it probably makes sense to use other triggers , like the Pub/Sub Messaging Service. In this interface, you can also define the environment variables for this function. Scroll down to Runtime, build., connections and security settings, and focus on the Runtime tab. Add the three values (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_NUMBER) you copied earlier.

Create function flow
Environment variables are bound to a single function and are not visible to other functions in your Google Cloud project. However, Google does not recommend storing API keys as environment variables. For storing secrets, they recommend that you use Secret Manager. For the purpose of this post, the environment variables are fine.

Hit Next to start implementing the Cloud Function.

Writing a Google Cloud Function in Node.js

The next user interface shows you the Inline Editor to implement the function. First, add the twilio dependency in the package.json.

{ 
  "dependencies": { 
    "@google-cloud/functions-framework": "^3.0.0", 
    "twilio": "4.21.0" 
  }
}

Then, implement the function that uses the twilio package to send SMS based on the provided request parameters. The account credentials will automatically be retrieved from the corresponding environment variables:

const functions = require('@google-cloud/functions-framework'),
   twilio = require("twilio"),
   client = twilio();

functions.http('helloHttp', async (req, res) => {
 const recipient = req.query.recipient || req.body.recipient,
     body = req.query.body || req.body.body;
   const message = await client.messages.create({
     body,
     from: process.env.TWILIO_NUMBER,
     to: recipient
   })
   res.send(`Sent message ${message.sid}!`);
});

Did you know that you can use almost the same code to send WhatsApp messages? The only requirement is that your sender is WhatsApp-enabled , and then you can prefix the from and to values with whatsapp:.

Once you click Deploy the Google Cloud Function will be available under a URL that looks like this one:

https://us-central1-<project-name>.cloudfunctions.net/send-sms

Your function is now isolated, autoscaled, and responds to HTTP triggers.

Send a Test SMS with the Google Cloud Function

Go to the Testing tab of the function to define the test event. Make sure to add a valid phone number as recipient and a body. Now you can either test this function straight from the Cloud Shell or from your local machine when you copy the CLI test command.

curl -m 70 -X POST https://us-central1-<project-name>.cloudfunctions.net/send-sms \
-H "Authorization: bearer $(gcloud auth print-identity-token)" \
-H "Content-Type: application/json" \
-d '{
  "recipient": "+4915112341234",
  "body": "Ahoy World"
}'

This command embeds another command (gcloud auth print-identity-token) to receive a valid auth token. This will only work if you are logged into the CLI tool with gcloud auth login. Or you use the Run in cloud shell feature in the GCP Console.

Did you receive your test message?

Screenshot of the received message
For real-world use-cases, it might also make sense to bundle multiple Cloud Function behind an API Gateway .

Conclusion

And voilà! You have conquered the art of sending SMS using Node.js and Google Cloud Functions. How cool is that? Not only can you fire off a message to anyone, anytime, but you can do so without breaking a sweat. All this is thanks to the power of Google Cloud and Twilio working hand in hand.

However, this is just the beginning of what's possible with cloud functions and SMS technology. Our next step is to show you how to handle incoming SMS messages, which opens another world of possibilities, such as chatbots that leverage AI.

Never stop exploring, for in the world of coding, every line holds the potential to unlock revolutionary possibilities. Keep experimenting, keep innovating, and stay obsessed with creating better communication with your customers.

I can’t wait to see what you build.