Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Structure my Application in Express.js ?

  • Last Updated : 07 Dec, 2021

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.

npm init

 



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.

touch app.js

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 

.env




PORT=3000 // This will be available as process.env.PORT
  
// You can write any variable here.


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.



app.js




// 3rd Party Modules
const express = require('express');
require('dotenv/config');
  
// Local Modules
const myRoute = require('./routes/myRoute.js');
  
// Server Initialization
const app = express();
const PORT = process.env.PORT;
  
// Middlewares
app.use(express.json());
  
// Routes will be written here
app.use('/route', myRoute); 
  
// Server Listen Along with Database 
// connection(in case of data persistence)
app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, 
                   and App is listening on port "+ PORT)
    else 
        console.log("Error occured, server can't start", error);
    }
);


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.

myController.j




// Methods to be executed on routes
const method1 = (req, res)=>{
    res.send("Hello, Welcome to our Page");
}
  
const method2 = (req, res)=>{
    res.send("Hello, This was a post Request");
}
  
// Export of all methods as object
module.exports = {
    method1,
    method2
}


myRoute.js




// 3rd Party Modules
const { Router } = require('express');
  
// Local Modules
const myController = require('../controllers/myController');
  
// Initialization
const router = Router();
  
// Requests 
router.get('/', myController.method1);
router.post('/', myController.method2);
  
module.exports = router;


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.

node app.js

After the server is successfully running we can start interacting with it, here is one example of GET request via browser,

Output:

Additional Points:

  1. 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.
  2. 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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!