Apium Innovations
Published in

Apium Innovations

Let’s set up an Express Server

Node.js is a platform to build server-side event-driven applications using JavaScript. It is a JavaScript runtime built on google’s open source v8 engine. Now express.js is an open-source and free web application framework for Node.js Even Though we can set up our server using node.js, using the express.js framework to set up a server has many benefits over node.js

One of the main reasons is that Express.js provides the most common Node.js features in the form of functions that we can use inside our applications. Instead of building things from scratch, we can use these functions to set up our backend. Express.js has middleware support and it also provides more advanced routing components.

In this article let’s see how to set up a simple express server. We are going to use some third-party middleware, and modules too. I’ll be explaining the benefits of using these packages and modules along the way.

So without further ado let’s get started!!!!

Before setting up our express server we need to install Node.js. If you want to check whether you have Node.js installed already, please run the below command in your terminal. Or else click here to install Node.js

check node version

Next, create a folder and open that folder using your favorite text editor. I’ll be using VS code and you can get it from here

Next inside the project folder, we can run the below command and set up a new npm package.

set up a new npm package with npm init command

This will create a package.json file at the root of our project.

package.json file

The Package.json file has all the basic information about our application. Whenever we install a new package using NPM it will be managed by the package.json file. we also define all the scripts we want to run, inside the package.json file.

Package-lock.json file is there to track the exact version of each and every package that we installed. In this way, we can maintain the consistency of our project by maintaining reproducibility even though packages are updated by their maintainers.

Next, let’s install express.js by running the below command in the terminal. This will create a new folder called node_modules at the root of our project. One important thing to remember is not to modify this node_modules folder. This has all the dependencies we installed when we are working on our project.

If you would like to read more about express.js you can visit their official website

command to install express.js

Next, we need to install nodemon. Now the difference is we are going to use this as a development dependency. With that when our application goes to the production stage development dependencies will not be included. These development dependencies are there to help us with our development process with various tips and hacks. And we need those only in the development environment.

We use nodemon to watch for all the file changes in our application and restart the server automatically for us instead of us doing that manually every time we modify a file in our project.

Below is the command for that

command to install nodemon
package.json file with devDependencies

Next, we need to install morgan, which is an HTTP request logger middleware for Node.js. With that, we can generate log files for all the traffic that comes to our application server. One of the main features of the morgan package is that it can use in both the development and production stages.

command to install morgan

Before installing the next npm package let’s try to understand what are environment variables and how to use those in our application.

When we are building applications we need those to run in different environments. These can be our local computer, internal company servers, cloud servers, or inside containers. With environment variables, we can make our application behave differently according to the environment it runs. We usually store all our environment-based configurations as environment variables.

Let’s assume we are building an application and we use some third-party API that provides us with an API key to complete the API request. We can use the API inside our application and store the API key as an environment variable and access it using the process core module of Node.js.

Now if we share our code with another person they can create their own API keys and use the application, without using the API key we created. We create a .env file inside the root of our project and store all the variables inside this file. The best practice is not to share this environment variables file with others as we usually store lots of credentials like client id, client secrets inside this file.

With that in mind, we can install our next npm package which is dotenv. This is a Node.js library that helps us to manage and load environment variables.

command to install dotenv

Next, we need to do some modifications to our package.json file.

Inside the scripts section, we can add a new script as below. Now with this when we run npm start script nodemon package will start to watch our index.js file for code changes

updated package.json file

Next, let’s create the index.js file and the.env file in the root of our project folder. We can store our configurations inside the .env file

With that, now we have the below folder structure.

folder structure

Inside our index.js we can write the necessary code to set up our express server.

setting up an express server

Let’s take a look at the code above and see what we have done there.

  1. we have required an express framework and stored it in the express constant.
  2. We have initialized the express framework we required earlier and saved that into app constant
  3. Next, we have decided on a port and saved that to port constant. Here I have selected port 3000 but you can select a suitable port you like.
  4. As the final step, we have a built-in listen method that takes our port number and a callback function as arguments. We have set up our callback function to log a message to the console whenever our server is running without any issue.

Now with that, if we run the below script we can see our server is running

running the server with the npm start command

Now let’s spice up code by adding more functionalities. For this let’s use the packages we installed and concepts we discussed earlier.

Let’s use our .env file to store our environment and the port we want to run our server.

.env file

Here we have defined node environment as development and port as 5000

Now let’s do the below changes to our code to use the defined environment variables

updated code

Here we have required the dotenv package we installed earlier and stored it in the dotenv constant. After that, we use the config method and pass the path to our .env file.

We need to define these at the top of our file for our code to use these environment variables we have defined inside the .env file.

Next, we have replaced the port constant value with the value we are getting from the .env file. Here we are asking to use the port value from the .env file or port 3000.

Now let’s see how to use morgan inside our application.

First, we can require morgan and store it in the constant named morgan. Next, we are instructing our application to use morgan if the node environment has been set to “development”. Morgan offers multiple presets including common, tiny, short and we are using dev here to log requests to the console.

use morgan inside our server

Let’s try to add some more code to make our express server more flexible.

I have added two more lines of code to our application. Now let’s try to understand the use of each of these code lines.

express.json() is a built-in middleware function in Express.js. This is very useful when we want to parse incoming JSON requests and put those data into the request.body. This expects requests to send data to our backend server in JSON format.

express.urlencoded() is another built-in middleware function in Express.js. This is also used to convert the request body to a more readable JSON format. But the difference between express.urlencoded() and express.json() is that with urlencoded we can convert form data to JSON format.

express server code

That’s it!! This is how we set up an express server. However, you can use more third-party packages and built-in methods according to your project requirements.

At Apium Innovations we build world-class software products while following the best practices in DevOps, follow us to learn more.

Thank you for reading!

Apium Innovations is a place which likes to challenge the norms. We like to add a bit of creativity to business, education and lifestyle. We like to say we add eccentricity to the generic mundane software.

Recommended from Medium

Which tools you need to develop web applications in ReactJS?

Some Basic Concepts of ReactJS

Lets Create a Github App using Github REST API in React.

Creating pages dynamically

Hmm…Let’s better know the famous VDOM

Hydrogen’s React-based Framework for Building Custom Storefronts on Shopify

Authentication with AWS Cognito and NestJS

Old Habits Die Hard, But Getting New Ones is Essential. Tips on Getting the Most Out of TypeScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jinali Pabasara

Jinali Pabasara

Software Engineer | Tech Enthusiast

More from Medium

How to create a CRUD operation using MongoDB and NodeJS?

3 ways of parsing data in Express

How to Build REST API with Node.js, Express, and PostgreSQL

Node JS : Node Module System