Skip to main content

Up and running Node.js

      What we are gonna do?

We will be creating a web app. A user can find gifs based on the word. To implement this we will be creating a backend service using Node.js, Express, and frontend using React. We will use Github for Source Code Management and finally we will deploy our project to AWS. We will also set up a pipeline for CI/CD (Continuous Integration and Continous Deployment).

Setup the development environment

This part you have to do on your own.

Fun part. Start coding.

Fire up the terminal if using ubuntu hit alt+ctrl+t.

Create a new directory for the project.

Image for post

Voila, npm will create a new package.json file.

Now let’s start writing code. We will use express for creating the backend server. Discussion about express is out of the scope for this post. Let’s pull express as a dependency from npm.

Image for post

npm will create a new package-lock.json file and node_modules directory.

Server

Writing and running the express server is pretty easy. Simply create a new file index.js and paste the below code.

var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Server is up and runnig on port 3000!');
});

Now let’s test our server. Run node index.js and visit http://localhost:3000/ to check your server in action.

Integrating with Giphy API

To integrate with Giphy we need GIPHY’s API. Go and create a new app in GIPHY and obtain the API key.

To make an API call to GIPHY API we need another npm package request and request-promise.

Run npm install request — save and npm install request-promise — save.

Once done. Let’s create a new API /gif. Update your code with the following snippet.

var express = require("express");
var app = express();
var request = require("request");
var rp = require("request-promise");
app.get("/", function(req, res) {
res.send("Hello World!");
});
app.get("/gif", async function(req, res, next) {
const options = {
uri: "https://api.giphy.com/v1/gifs/search",
method: "GET",
qs: {
api_key: "<API_KEY>",
q: req.query.search,
limit: 3,
offset: 0,
rating: "G",
lang: "en"
}
};
const response = await rp(options);
res.json(response);
});
app.listen(3000, function() {
console.log("Server is up and running on port 3000!");
});

Now restart the server. And the endpoint

http://localhost:3000/gif?search=shashi

And you can see the returns response from GIPHY’s search API. Now our backend is ready to deploy.

Deployment (Not a rocket science)

Prerequisites

All set?

Github

Let's initialize the repository, run git init.

Image for post

Create a new file .gitignore and paste the following content.

node_modules

Now run some more git commands:

git status

git add .

git commit -m “awesome commit message”

git remote add origin <YOUR_GITHUB_REPOSITORY_URL>

git push origin -u master

Provide your username and password.

At this point, you have successfully pushed your code to GitHub.

AWS Server

Login to your AWS console.

Image for post

Click on the Launch Instance button.

Image for post

Scroll down and click on the Select button for Ubuntu Server.

Image for post

Go ahead with the auto-selected t2.micro instance. Click on the Review and Launch button.

Image for post

3, 2, 1, and click on the Launch button.

Image for post

Choose “Create a new key pair” from the dropdown menu. Input the name. And download the key. It will download a .pem file.

KEEP THIS KEY FILE SAFE AND DON’T LOOSE IT. YOU WON’T BE ABLE TO DOWNLOAD IT LATER.

Image for post

Once you have downloaded the file. The Launch Instance button will be activated. Click on the Launch Instance button to launch a new instance.

Image for post

Awesome we have just launched a new AWS EC2 instance.

Navigate to Services -> EC2 to view the instance.

Image for post

Well done.

Now scroll to the right side and click on launch wizard.

Image for post
Image for post

Click on the Inbound tab on the down.

Image for post

Click on Edit

Image for post

Click on Add Rule

Image for post

Give Port Range as 3000 and select Source as anywhere and Save. This will allow our incoming traffic on our server on port 3000 from anywhere over TCP protocol.

Well done.

Now let's deploy our backend service on the EC2 instance. For now, we will do it manually.

Select your instance and click on connect. You will see instructions on how to connect to the EC2 server.

Image for post

Give the 400 permission to your .pem file.

sudo chmod 400 <KEY>.pem

Now we are ready to connect with our server using SSH. Execute the following command.

ssh -i <KEY>.pem ubuntu@ec2–13–127–93–105.ap-south-1.compute.amazonaws.com

Image for post

if prompted write yes and enter. You will be connected to your EC2 instance.

Image for post

Setting up the server.

Let’s set up our server to host our application.

sudo apt-get update

Install Node.js and npm.

sudo apt-get install nodejs

sudo apt-get install npm

Clone your repository.

git clone <YOUR_REPOSITORY_URL>

cd <PROJECT>

Install npm dependencies

npm install

Start the server

node index.js

Now go to <YOUR_EC2_PUBLIC_IP>:3000/gif

Woah you have deployed your application on the server.

Next, we have to do some more things.

2. Setup CI/CD pipeline for automatic deployment of our application.

Thanks for reading. If you have some feedback, please provide your response or reach out to me on Twitter or Github.

Comments

Popular posts from this blog

Track stock market information right in your Terminal.

     Introduction: As a developer, I love working with the terminal. The plain, simple, and in my opinion the best way to interact with the computer (also it makes you look geeky). I spent most of my time in the terminal. By now you must have guessed I am a huge fan of the terminal and terminal-based applications. Recently I developed an interest in stock markets and started tracking the stock markets. Since I love working with the terminal I decided to build a terminal oriented application that can help me to track the stock market. Inspir e d by  wttr.in  I build  terminal-stocks  which can provide the stock's current prices, historical prices, and global market summary. How to use terminal-stocks terminal-stocks  is available and can be used without installation. Get the current price of the stock. curl terminal-stocks.dev/ITC.NS Current price of stocks You need to provide the ticker of the stock and terminal-stocks will give you the price information of the stock.  terminal-st

Setting up Nginx as a reverse proxy for Node.js App

Okay.. but what is a reverse proxy? A reverse proxy is a web server that centralizes internal services and provides unified interfaces to the public. Requests from clients are forwarded to a server that can fulfill it before the reverse proxy returns the server’s response to the client. Nginx is a popular choice to use as a reverse proxy for your node.js application. Got it. Now let’s set up Nginx Let’s say your nodejs server is running locally on localhost:3000. We will set up Nginx to get the request and forward the request to our nodejs server. Ins t alling Nginx on ubuntu sudo apt-get update sudo apt-get install nginx Configure Nginx Disable the default, virtual host unlink /etc/nginx/sites-enabled/default 2. Create a configuration file cd /etc/nginx/sites-available sudo nano reverse-proxy.conf 3. Put the following content in the file server { listen 80; listen [::]:80; access_log /var/log/nginx/reverse-access.log; error_log /var/log/nginx/reverse-e

RESTful CRUD API with Deno, Oak and MongoDB

In this post, we are going to build a RESTful CRUD API with Deno, Oak and MongoDB as database. In the previous article, we discussed how to install deno in your local machine and start using Deno. If you haven’t read that article, please read the article below and install the deno first. Getting started with Deno, Your first app Hello Deno. Let's install Deno. Deno ships as a single executable with no dependencies. You can install it using the installers… blog.shashi.dev After installing the Deno, we will start building the restful crud api’s. We will use o ak  microframework. Some of the other deno microframeworks are: abc deno-drash deno-express oak pogo servest In this article we will be using oak, which is inspired by koa. Setting up the project: Create a new directory called  restful-api-deno mkdir restful-api-deno 2. After c r eating the directory just  cd  into the directory cd restful-api-deno 3. Create a new file  server.ts  and paste the following code init. import { Ap