Building A Node.js - Express App (covid19-updates)|Part-1
Tags: twiliohackathon, node, javascript, showdevs
Published: 2020-04-09 14:19:34

## Brainstorming

Last week Dev.to announced a [hackathon](https://dev.to/devteam/announcing-the-twilio-hackathon-on-dev-2lh8) 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](https://www.twilio.com/docs/sms).
___
## 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](https://expressjs.com/) 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](https://www.mongodb.com) 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)

- [Node.Js Tutorial For Beginners | Dev Ed](https://www.youtube.com/watch?v=zQRrXTSkvfw)
- [Build A Restful Api With Node.js Express & MongoDB | Dev Ed](https://www.youtube.com/watch?v=vjf774RKrLc&t=515s)
- [Express Tutorial - MDN Docs](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website)
- [MongoDB Crash Course | Traversy Media](https://www.youtube.com/watch?v=-56x56UppqQ&t=358s)

___

## 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.
```bash
$ npm init
```

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

```bash
$ npm install express nodemon mongoose
```

[mongoose](https://mongoosejs.com/) 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](https://www.npmjs.com/package/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.

```javascript
// 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') );
```

Now, we can run this script with following code in terminal and it will run just fine.
```bash
$ node app.js
```

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.

```json
"start": "nodemon app.js"
```

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](https://expressjs.com/en/guide/using-template-engines.html) 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.

```bash
$ npm install ejs express-ejs-layouts
```
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
```javascript
const expressLayouts = require('express-ejs-layouts');

app.set('view engine', 'ejs');
app.use(expressLayouts);
```

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
```

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.

```javascript
// 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') );
```

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.](https://nodejs.org/api/modules.html)

```javascript
module.exports = {
	app.get('/'(req,res) => {
		res.render('index.ejs');
	});
}
```

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 https://github.com/jamesshah/covid19-updates %}

Thank you for reading!! 
#####HappyCoding👩‍💻 👨‍💻