Build a text messaging app with Vuejs, Node and Twilio
In this article, we will build a text messaging app using Nodejs, Twilio, and Vuejs. Twilio is a cloud-based service that enables powerful communication between mobile devices, applications, services, and systems throughout the business in order to bridge the gap between conventional communication.
Prerequisites
- Familiarity with HTML, CSS, and JavaScript (ES6+).
- Vs code or any code editor installed on your development machine.
- POSTMAN installed on your development machine.
- Basic knowledge of Vuejs.
- Basic Knowledge of Expressjs
Before we continue lets head over to https://www.twilio.com/ and create an account.
Click on the Signup button to create a new free account. Once you are done with the signup process, you should see your Console Dashboard. This is where you will find your Twilio credentials, checking your usage, procuring a phone number and more.
After the signup process, you need to verify your personal phone number for some security reasons. To do that click on the menu option on the left-hand side to open up the menu bar. Click on “Phone Numbers” which will take you to Number management page:
On the page click on verified callers Id
and then click on the red plus button to add a new number. Ensure that you input the correct number. A verification code will be sent to that phone number which you will be prompted to input in the input field.
After doing this, you will need a Twilio-enabled phone number (a phone number purchased through Twilio) to send messages or make phone calls using Twilio. To get that, click on the “Get started” nav item on the sidebar and then click the red button to create your first Twilio enable phone number:
By Default, Twilio will provide an Account SID
and an Auth Token
which we will be used for authentication in our nodejs app. To view that go to the Dashboard tab on your console:
Now that we have all this Credentials lets start building our application.
Let’s start by creating our backend, let create a new folder for our application and then initialize a new node project. To do that open up your terminal and type the following:
cd desktop
mkdir twilio-vue && cd twilio-vue
mkdir server && cd server
npm init -y
code .
The npm init -y
command creates a package.json
file for our application. This is where our application dependencies will be stored. The code .
command will open up that folder in VS code which is our text editor.
Now let’s install the dependencies for our application, Run the following command on your terminal:
npm i --save express twilio body-parser nodemon cors dotenv
The command to pull Express, Twilio SDK, body-parser, morgan and nodemon into our development environment.
Body-parser is a piece of express middleware that reads a form’s input and stores it as a javascript object accessible through req.body.
Nodemon will watch our files for any changes and then restarts the server when any change occurs.
Express will be used to build our nodejs server.
cors
is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.
dotenv
will store all of our environment variables. This is where we will store our Twilio account SID and our Twilio Auth Token.`
Create A Nodejs Server
We now have to create our application files,to do that open up your terminal and type the following:
touch index.js && touch .env && touch .env.example && touch .gitignore
This will create an index.js
file, this is where will build our server, The .env
file will be used to store our environment variables, the .env.example
file is used as an example file for you to know what KEY=VALUE pairs you need for your project which has been defined in the .env
file.The .gitignore
file is a text file that tells Git which files or folders to ignore in a project when pushing to a repository.
Lets start by adding this to our .gitignore file:
node_modules
.env
Git will ignore this files when pushing to a repository.Now lets create a simple Express Server and configure the dependencies.Open up the index.js
file and add the following:
require('dotenv').config()
const app = require('express')();
const bodyParser = require("body-parser");
const cors = require("cors");
const PORT = 3000
app.use(cors());
//config
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//configure body-parser ends here
app.get('/', (req, res) => {
res.status(200).json({
message: "Wisdom is Saaying,Hello Twilio"
});
});
app.listen(PORT, () => {
console.log(`App is runing on prot ${PORT}`);
});
Now we can run our application by running :
nodemon index.js
This will open up our application and run it on port 3000
.
Configuring Twilio
Now we have to configure the Twilio SDK into our express application. First we need to bring in Twilio into the application by requiring it:
const twilio = require('twilio');
After doing this we need to bring in our Account SID
and our Auth Token
:
const accountSid = proccess.env.ACCOUNT_SID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
Now head over to the .env file and add your Account SID and your Auth Token:
ACCOUNT_SID=***************************
AUTH_TOKEN=***************
TWILIO_NUMBER=***********
Replace the asterick with your account credential and the add this to your .env.example file:
ACCOUNT_SID=<your account SID>
AUTH_TOKEN=<your auth token>
TWILIO_NUMBER=<your Twilio phone number>
This will help anyone that clones your project to know what is require to run the project.
Now we need to create a POST route that will send the sms to our preffered phone number:
app.post("/send-message", async(req, res) => {
try {
let response = await client.messages.create({
body: req.body.message,
from: process.env.TWILIO_NUMBER,
to: req.body.to
})
res.status(200).json({
response: response,
message: `Message Sent To ${req.body.to}`
})
} catch (err) {
console.log(err);
res.status(500).json({
Error: err
})
}
})
The client.messages.create
instance handles the sending of messages which take in 3 properties: from, to and body. The body-parser gives us the ability to make use of the req.body to pass form values in our application. Note that to send messages you have to register the numbers, if you don’t do this it will throw an error:
Now lets test our application by using POSTMAN to test our /send-message
endpoint.
After making this request you will receive a text message. You could head over to you Twilio console where you have programmable SMS to see all the logs:
Since we have that working we can now start working on the frontend.
Setting Up The Frontend For our text messaging app
Let’s create a new directory client and then move into that directory. This is where we will be creating our Vue application:
cd desktop
cd twilio-vue
mkdir client && cd client
vue create twilio-messenger
Running the vue create twilio-messenger
will create a new Vue application. Before that, you will be asked some questions to set up the application.
STEP 2
To select and control an item on the list you can use your arrows to move up and down and then press the spacebar when you want to select/deselect a feature.
STEP 3
Select package.json file for your config store
STEP 4
If you want to save this as a preset you can by typing Y, if not type N and press enter. When the Vue CLI finishes creating our application, we’ll open up the twilio-messenger
folder in our text editor.
To run the Vue app run the following codes on the terminal:
cd twilio-messenger
npm run serve
After compiling, it will be outputted on the terminal that the application is running on port http://localhost:8080/
.
Note that the port number might differ on some local machines.
Accessing http://localhost:8080/
on our browser we will have this displayed:
Now that we have successfully created the Vue application, We can now start writing some code. Before we do that, let’s clean up the UI. To do this head over to src/components/HelloWorld.vue
and replace the code with this:
<template>
<div>
<h1>Twilio App</h1>
</div>
</template>
<script>
export default {};
</script>
We now have to install Bootstrap and Axios in our application. Bootstrap will be used to customize our user interface, Axios will be used to handle all our HTTP request and response and sweetalert will be used to display Success and Error messages.
To install that open up the terminal and type:
npm install vue bootstrap-vue bootstrap axios sweetalert
After installing this we need to register it in the main.js so that we can use it globally in our application.
import {
BootstrapVue,
IconsPlugin
} from 'bootstrap-vue'
Vue.use(BootstrapVue)
Vue.use(IconsPlugin)
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
This will register and configure Bootstrap globally in our application.
Now, lets set up our User interface for our application. Modify The code in src/components/HelloWorld.vue
to this:
<template>
<section>
<div class="container">
<div class="row">
<div class="col-md-4 offset-md-4">
<div class="card p-4">
<h1>Twilio App</h1>
<form>
<div class="form-group">
<label for="Number">Enter Phone Number</label>
<input type="text" placeholder="080********" class="form-control" required />
</div>
<div class="form-group">
<label for="Number">Enter Message</label>
<textarea class="form-control" id cols="30" rows="10" required></textarea>
</div>
<button class="btn btn-primary">
<span v-if="loading" class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>Send
</button>
</form>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
import swal from 'sweetalert'
import axios from 'axios
export default {
data() {
return {
loading:false
}
}
};
</script>
After doing this you will get this on your browser:
We added a spinner to the send button and set it to false by default. This spinner will be set to true when the sending process is on.
Now let define a data property to hold the value of our form:
message: {
to: "",
message: ""
},
And then we have to bind the values to our input fields:
<div class="form-group">
<label for="Number">Enter Phone Number</label>
<input
v-model="message.to"
type="text"
placeholder="080********"
class="form-control" required
/>
</div>
<div class="form-group">
<label for="Number">Enter Message</label>
<textarea
v-model="message.message"
class="form-control"
id
cols="30"
rows="10"required
></textarea>
</div>
We now need to add a submit event listener to our form that will handle the submitting of the form:
<form @submit.prevent="sendMessage">
Having done that we need to define the method:
async sendMessage() {
try {
let response = await axios.post(
"localhost:3000/send-message",
this.message
);
console.log(response);
} catch (err) {
console.log(err);
}
}
Now fill the form, make sure that the number inputted is a register Twilio number, else it will a throw an error.
We can now use sweet alert to handle the success response or any error response that we get and we can set the loading property to true the process is on so that the user can know when the process is on. So let’s modify our method to this:
methods: {
async sendMessage() {
this.loading = true;
try {
let response = await axios.post(
"http://localhost:3000/send-message",
this.message
);
console.log(response);
swal("Success", response.data.message, "success");
this.loading = false;
} catch (err) {
swal("Error", "Something Went Wrong", "error");
this.loading = false;
console.log(err);
}
}
}
Now if we make a request the loader displays letting the user know the process is on,and if the request is successful we will get this:
And if you try to send a message to a non-verified Twilio number you will get this error:
We could see all the log in our Twilio dashboard to keep track of Message that is sent, delivered and unsuccessful messages:
Conclusion
In this article, we learned hot to build a simple messaging app using the Twilio service. We can also create other applications like a calling app, WhatsApp messager and other cool applications using the Twilio services.
Source code here