Twilio sms sending in express

To send SMS messages using Twilio in Express, follow these steps:

  1. Install the Twilio package: Begin by installing the Twilio package from npm. Open your terminal and run the following command:
npm install twilio
  1. Import the Twilio module: In your Express application file, import the Twilio module using the require() function:
const twilio = require('twilio');
  1. Set up Twilio credentials: Obtain your Twilio Account SID and Auth Token from the Twilio Console. Create a new instance of the twilio module by passing your credentials as parameters:
const accountSid = 'your_account_SID';
const authToken = 'your_auth_token';
const client = new twilio(accountSid, authToken);
  1. Define a route for sending SMS: Create a route in your Express application to handle the SMS sending functionality. Inside the route, use the client.messages.create() method to send an SMS:
app.post('/send-sms', (req, res) => {
  const { to, body } = req.body; // 'to' represents the recipient's phone number, and 'body' is the message content

  client.messages
    .create({
      body: body,
      from: 'your_twilio_phone_number',
      to: to
    })
    .then(message => {
      console.log(message.sid); // Output the message SID to the console
      res.send('SMS sent successfully');
    })
    .catch(err => {
      console.error(err); // Output any errors to the console
      res.status(500).send('Failed to send SMS');
    });
});
  1. Test the SMS sending functionality: Start your Express server and test the SMS sending functionality by making a POST request to the /send-sms route. Ensure that the request body contains the recipient's phone number in the to field and the message content in the body field.

That's it! You have successfully set up Twilio SMS sending in Express. Remember to handle any errors appropriately and customize the route according to your application's requirements.