Open In App

Why Express ‘app’ and ‘server’ files kept separately ?

Express is a simple and minimalistic framework for web applications in Node.js. Express provides a rich collection of features for development of both web and mobile applications. In any web or mobile application, each module or layer should be only responsible for a single task and should not deal with other tasks. This allows the application to be broken into smaller building blocks, which helps in reducing code complexity and data to be abstracted from other layers.

Applying a similar concept to the project structuring of Express, the separation of the application logic from the server allows the code to be modular and follow a MVC (Model-View-Controller) model. The separation is essential to reduce coupling and to encapsulate and abstract the inside logic of application.



Each of the components and their responsibilities in Express are discussed below:

Server: The server is responsible solely for the initialization of the middleware, setting up the engine, and the routes through which requests are made. These routes consist of the main application or function logic.
Below is the code snippet of what goes into the server.js file.






// A function to initialize the server
// configuration, middleware and routes
const server = express();
  
create = function (config) {
      
    // Get routes from routes directory
    let routes = require('./routes');
  
    // Configure the server settings
    server.set('env', config.env);
    server.set('port', config.port);
    server.set('hostname', config.hostname);
  
    // Returns middleware that parses json
    server.use(bodyParser.json());
  
    // Set up routes for the server
    routes.init(server);
};

App: The ‘app’ file contain the main business logic of the web application and is responsible for its execution. It also contains access to the backend database and data models. The ‘app’ consists of two main components – routes and controllers. These are discussed below.

Advantages of ‘server’ and ‘app’ separation:


Article Tags :