How to Structure my Application in Express.js ?
Express is a minimalistic framework that is used to create web servers. It is built upon the HTTP module of node.js and provides a much easier way to manage the code related to the server.
In this article, we are going to discuss how we can structure our express application.
Create Node Project:
Step 1: As the express application is built upon NodeJS so first of all, we have to initialize a node project, write the command below in your terminal.
Step 2: Install Packages
npm install express
Step 3: Create an app.js file. In this file, we write the entire code of the server.
Project Structure: After all of this, our project structure will look like this.
Configure the environment variable: While writing server code several times we need some constant variable in the entire codebase, so we should set some kind of environment variable so that it can be available in all files.
This module is used to load environment variables from the .env file to the process object so that later we can easily use these variables anywhere in the codebase.
npm install dotenv
Structure of app.js file: Imports are the first thing that should be written inside this file and then some kind of initialization can be there, and later there should be middlewares which are related to entire routes. For example, it can be the express.json() middleware which is used to parse the incoming requests as JSON. After all of this, we can write our routes to execute the particular functionality when the user requests the URL which is starting from the string given inside the middleware.
In the end, we can start our server to listen to the client requests. It is safer to establish the database connection first if we are concerned about data persistence.
Setting up Controllers and Route: Routes are the endpoints of HTTP requests to the server or can say a few ways through which a client can interact with the server, we often need a lot of routes in our app so it is a convenient way to set them up beforehand.
The controllers are nothing but the code which is going to execute when a client accesses some route. This code can consist of several lines that’s why we separate it from routes files.
Step to run the application: We can run our express application with the command below, The app.js is the entry point of this application.
After the server is successfully running we can start interacting with it, here is one example of GET request via browser,
- While running the server with node command it keeps running on the basis of the last saved files, if you want the server to be interactive and want to re-run the server every time the code changes, you can use nodemon.
- Usually, the server is made up of several APIs so that clients can interact, in case if you want to log details of requests which are striking on the server, you can use morgan. It’s just a convenient way to know what’s going on the server.