DEV Community

James Shah
James Shah

Posted on • Edited on • Originally published at Medium

Building A Node.js - Express App (covid19-updates)|Part-1

Brainstorming

Last week Dev.to announced a hackathon in collaboration with Twilio to make a web app using any of the Twilio APIs, So I decided to participate and build something in this quarantine time which will help me learn some new tech and build a project to showcase.

So I started brainstorming for an idea to create an app for and just then I heard my mother saying that we are privileged to have an Internet service which helps us getting latest news and updates in this Covid-19 lockdown period but for those who doesn't have this privilege, It's hard to get information about new cases in their state as well as in the country.And bingo!! I got the idea to create my web app.

I decided to create a web app in which user can register with their phone number once and they can get daily updates of new cases in their area as well as in the country with the help of Twilio Programmable SMS API.


Deciding Tech-Stack

Now it was time to choose the Tech-Stack that i will be using to create this web app.I've created web apps using Django and Flask(Python Web Frameworks) in the past,and I am pretty much used to creating backend in Python but I wanted to learn new Stack and so I decided to take on Node.JS & Express Framework for this web app and for database, I've used SQL Databases (MySql, PostGreSql) in past and I wanted to learn NoSql Databases, so I decided to learn MongoDB by implementing it in this project. And That's it. I was ready with the Idea and Technologies to use in my mind and I started searching and learning basics about these techs from here and there.

Some Recommended Resources To Start Learning Node.Js, Express And MongoDB (Pre-requisite : Vanilla Javascript)


Creating Package.json & Installing Dependencies

After all the tutorials and documentation reading, it was time to get my hands dirty and writing some code.

Any node application is generally started by creating a package.json file. This file keeps record of all the dependencies used in your application and every information about your project. It is very essential as you cannot upload all your installed node modules online,let's say Github or GitLab. So using this file you can install all the dependencies on the go.

You can create such file by writing following code in the terminal.

$ npm init
Enter fullscreen mode Exit fullscreen mode

Now let's install express and some other useful npm packages by writing the following line in terminal.

$ npm install express nodemon mongoose
Enter fullscreen mode Exit fullscreen mode

mongoose is an object modeling package for node.js which helps us to connect to our MongoDB database and create model for our database.
And nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

As soon as these packages get installed, you can check in your 'package.json' and you will see that in dependencies these packages along with their installed versions are stored.


Creating Express Server And Writing First Route

After installing the express, I started writing my first route in express in the app.js file.

// Importing express in our app
const express = require('express'); 
// Creating express app instance
const app = express.app();

//First Get Route
app.get('/', (req,res) => {
    res.send("Hello World. This is my first route in express!")
});

// Start listening on port 3000.
app.listen(3000, () => console.log('Server Up And Running. Listening On Port 3000') );
Enter fullscreen mode Exit fullscreen mode

Now, we can run this script with following code in terminal and it will run just fine.

$ node app.js
Enter fullscreen mode Exit fullscreen mode

But as I've mentioned before, we'll be using nodemon so that we don't have to stop and rerun our server after every change and so now we'll add an npm script in our package.json file as below.

"start": "nodemon app.js"
Enter fullscreen mode Exit fullscreen mode

And now, all we have to do is write npm start
and nodemon will run our server whenever we change any file in our project.

Then, By visiting http://localhost:3000 I could see my server up and running with my response to the index('/') route as it is.

But we don't want to just send single line responses in our website but we want to send styled html pages to our users.We can do so by Rendering HTML files using many different template engines such as Jade, EJS, Pug, Mustache, etc.


Rendering HTML files using EJS template engine

I decided to use EJS because in this application I won't need much complex front-end. To use EJS, first we have to install EJS using npm.

$ npm install ejs express-ejs-layouts
Enter fullscreen mode Exit fullscreen mode

This, express-ejs-layouts package helps us create HTML code blocks and use them in in different HTML files to reduce the code redundancy.For example, we can create a basic layout in which we can create the basic HTML structure and then we don't have to repeat the head, title, meta, body tags again in every file.

To use EJS and express-ejs-layouts, we'll have to add following lines in our app.js file

const expressLayouts = require('express-ejs-layouts');

app.set('view engine', 'ejs');
app.use(expressLayouts);
Enter fullscreen mode Exit fullscreen mode

Now we can render HTML files into our application and using EJS we can also use variables in our HTML code. Now we can write HTML code in our route response but wait, we shouldn't mix our front-end with our back-end in the same file right? Because, that will make debugging task backbreaking and our code will be unreadable.

Also, We won't be writing routes in this app.js files as well for the same reason as above. So now is a good time to restructure our code before it gets unmanagable and tiresome.


Restructuring Project Directory

Directory structure is a very important point in any project and therefore, we will choose the best practice to create our project structure.

Below is the restructured project directory.

covid19-updates/
  views/
    index.ejs    
  routes/
    index.js
  app.js
  package.json
Enter fullscreen mode Exit fullscreen mode

We'll have to make some changes in our app.js file as well. We'll have to set views directory so that our server will know where to search for our HTML files that we want to render and also we'll have to import route in app.js file.Let's see how our app.js file looks like after these changes.

// Importing express in our app
const express = require('express'); 
// Creating express app instance
const app = express.app();

const expressLayouts = require('express-ejs-layouts');

app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.use('expressLayouts');

// To serve Route
require('./routes/index')(app);

// Started listening on port 3000.
app.listen(3000, () => console.log('Server Up And Running. Listening On Port 3000') );
Enter fullscreen mode Exit fullscreen mode

And now in routes/index.js file we'll have to export the module that we've created for our index('/') route using module.exports.
Note: In node.js, every file is treated as a module. Read more about modules in node here.

module.exports = {
    app.get('/'(req,res) => {
        res.render('index.ejs');
    });
}
Enter fullscreen mode Exit fullscreen mode

Though, using Router Middleware to serve routes of same prefix is the best practice in an express app.
And what in the name of god are Middlewares,now?? Well, that's a whole another article. For now, we are ready with our index route with HTML file as response!!

Full code can be found at this repository :

GitHub logo jamesshah / covid19-updates

Simple web app to send daily covid-19 cases updates to users.

covid19-updates (India)

Simple web app to send daily covid-19 cases updates to users using Node, Express.js, Twilio Api and some other packages.

GitHub license

About

This application uses Twilio API to send daily covid-19 cases updates to the registered users.
Data Source - Covid 19 India API (Unofficial)
This web app is a part of Dev-Twilio Hackathon on dev.to

How it works

Users register with their Name, Phone Number and State (currently only Gujarat and Maharashtra is available) and they will get daily updates of cases in their state and in India, twice a day(9 am & 8 pm) via SMS (Twilio SMS Api)
User can choose to stop the service by sending "STOP" to the number(Twilio Number).

Features

  • Node.js web server using Express.js
  • Basic web user interface using EJS for templating and Bootstrap for UI
  • User interface to register
  • Project Specific environment variables using .env files.

Usage

Requirements

Thank you for reading!!

HappyCoding👩‍💻 👨‍💻

Top comments (0)