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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
};

chevron_right


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.

  • Routes: Routes, as the name suggests, are responsible for defining the routes within the application. Code snippet for defining routes in routes/index.js.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // routes/index.js
    server.get('/', function (req, res) {
      
        // Redirect request to /home route 
        res.redirect('/home');
    });
      
    server.use('/home', apiRoute);
    server.use('/contact_us', homeRoute);
    server.use('/about', errorRoute);

    chevron_right

    
    

  • Controllers: The controllers contain the logic to be executed. They also control the views rendered. Code snippet for defining controllers.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // controllers/home.js
    function index (req, res) {
        console.log("On the home page");
      
        // Write any other application logic here...
    }

    chevron_right

    
    

Advantages of ‘server’ and ‘app’ separation:

  • Data Abstraction and Encapsulation: While the server consists only of logic that deals with server configuration, setting up the middleware and initializing the routes, the app takes care of the application logic and abstracts the data model and business logic from the server layer. This ensures that the database/data is abstracted from the server layer and encapsulated by the application layer.
  • Modularity: By keeping the server and app functionalities separate, the code is divided into multiple modules, each having a single task or responsibility to perform. These can be individually used whenever required as there is a reduced dependency between modules. Duplicate code can be avoided through a clear separation of logic.
  • Scalability: Each individual component is assigned a unique responsibility. This allows changes to be made quickly without having to make changes everywhere in the code. For example, consider the logic of a module that is to be changed, which is being used as a submodule in several other functions. If the logic is a separate module, the change would only have to be made in that one module, instead of all the functions in which the usage of logic occurs.
  • Reusability: Since the application is divided into multiple modules that are assigned a single task, they can be reused in the application multiple times whenever the need be. For example, an application requiring the conversion of minutes into seconds multiple times might define this conversion as a separate function, to avoid the hassle of re-writing the logic throughout the application again and again.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.