Let’s set up an Express Server
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
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.
This will create a package.json file at the root of our project.
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
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
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.
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.
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
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.
Inside our index.js we can write the necessary code to set up our express server.
Let’s take a look at the code above and see what we have done there.
- we have required an express framework and stored it in the express constant.
- We have initialized the express framework we required earlier and saved that into app constant
- 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.
- 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
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.
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
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.
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.
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!