Jason Jolt
Jason Jolt

Reputation: 90

How to send an SMS using Twilio through frontend with react?

I've read the Twilio documentation and I can't find a way to send a simple SMS from the frontend using JavaScript/React.

The Twilio documentation just shows how to do that using Node.js(server side).

Actually, I found the documentation a bit awkward because they don't explain the how to do that using the most common programme language on the web.

I'm using postman and it works fine, but on my react code doesn't. The code below was exported from Postman:

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://api.twilio.com/2010-04-01/Accounts/AC62761f2bae5c5659cc5eb65d42e5d57e/Messages.json",
    "method": "POST",
    "headers": {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Basic hashedAuthToken",
            "Cache-Control": "no-cache",
            "Postman-Token": "0s41f5ac-2630-40c4-8041-1e5ee513f20d"
    },
    "data": {
            "To": "+353838173123",
            "From": "+18634000432",
            "MessagingServiceSid": "MG3d622e63a343e11a2032b1414560f227",
            "Body": "Test, hi"
    }
}

$.ajax(settings).done(function (response) {
    console.log(response);
});

PS: The tokens above was modified. It won't work if you are not using your own credential.

Upvotes: 2

Views: 4533

Answers (2)

philnash
philnash

Reputation: 73029

Twilio developer evangelist here.

There is a huge problem with what you are trying to attempt here.

Putting your Twilio credentials into the front end (or into a Stack Overflow question/answer) leaves them open to anyone to read your source code and steal them. A malicious attacker can take those credentials and abuse your account with them.

I recommend you refresh your Auth Token in your Twilio console now. You should consider them compromised.

What you should do is build an SMS sending service on your own server side and then call that service from your React front end. There is a blog post on sending SMS with Twilio on React that is worth reading and I will try to put something together to show it too.

Update:

I wrote a blog post explaining how to send an SMS with React and Twilio. The important thing is that you should perform the API call in your server (in the blog post, it's an Node.js/Express server but you can use whatever server-side tech you want). Then you send the message from your React application to the server using fetch (or axios or XMLHttpRequest if you want).

Upvotes: 1

1156752
1156752

Reputation: 4013

You can use the method below to do that easily.

sendSMSTwilio(message) {
    const url = Config.sms.url;

    const accountSid = Config.sms.accoundId;
    const authToken = Config.sms.authToken;
    const auth = 'Basic ' + new Buffer(Config.sms.accountSid + ':' + Config.sms.authToken).toString('base64');

    const details = {
        To: message.to,
        From: message.from,
        MessagingServiceSid: Config.sms.serviceSid,
        Body: message.text
    };

    const formBody = [];
    for (var property in details) {
        const encodedKey = encodeURIComponent(property);
        const encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + '=' + encodedValue);
    }
    const body = formBody.join('&');

    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            Authorization: auth
        },
        body
    };

    return new Promise((resolve, reject) => {
        return fetch(url, options)
            .then((response) => {
              return resolve(response);
            })
            .then((responseJson) => {
              return resolve(responseJson);
            })
            .catch((error) => {
              return reject(error);
            });
        });
  }

You can call and receive the promise response like that:

this.sendSMSTwilio()
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log('Error SMS sender', err);
  });

Upvotes: 0

Related Questions