Learn Express.js Β· 5/14

Application Architecture & Express Router

8 min read

Application Architecture & Express Router πŸ—οΈ

Welcome to the architectural phase of your Express.js journey. So far, you have likely been writing all your server code inside a single index.js or app.js file. That works perfectly when your application is small. But what happens when your application grows?

Imagine opening an index.js file and scrolling for 45 minutes just to find the /login route. By the time you find it, your coffee is cold, and you have forgotten what bug you were trying to fix.

In this guide, we will learn how the industry structures Express applications to keep code organized, scalable, and maintainable.


1. The Problem with Single-File Apps: Monolith vs Modular πŸ“¦

The Problem

When you start an Express project, it is tempting to put the server setup, database connection, middleware, and every single route (users, products, orders) into one giant index.js file.

As you add more features, this file grows into a 5,000-line monster. In a team setting, if three developers are working on different features, they will all be editing the same file. This leads to massive version control merge conflicts, slow development, and extreme developer fatigue.

The Concept: Monolithic vs Modular

  • Single-File (Monolithic) Structure: All logic, routing, and configuration live in one unified block of code.
  • Modular Structure: Code is divided into smaller, independent, and interchangeable modules based on their specific responsibilities.

The Solution

We solve the single-file problem by adopting a modular approach. Instead of keeping everything in one place, we split the application into multiple files and folders. Think of it like a well-organized department store. Instead of dumping electronics, groceries, and clothing into one giant aisle, you create separate departments. If a customer wants a TV, they go straight to the electronics department. If you need to fix a user-related bug, you go straight to the user module.


2. Using express.Router() to Group Related Routes πŸ”€

The Problem

If we want to split our massive index.js file into smaller files, how do we actually do it? We cannot simply create a new file, write app.get(), and expect it to work, because the app object was created in index.js. Creating a new express() app in every file would create multiple separate servers, which is not what we want.

The Concept: express.Router

express.Router is a class built into Express that allows you to create modular, mountable route handlers.

Under the hood: A Router instance is essentially a "mini-application" that only performs middleware and routing functions. It does not start a server or listen on ports. It acts as a container for routes that can be plugged into your main application.

The Solution

We use express.Router() to group related routes together in their own files (e.g., all user routes in userRoutes.js) and then "mount" or connect that router to the main application.

Industry Practice: Building a Router

Step 1: Create the Router File (routes/userRoutes.js)

javascript
const express = require('express');

// Create a new router instance
const router = express.Router();

// Define routes on the router, NOT on the app
// Note: The path here is relative to where it is mounted. 
// We will mount this to '/users', so '/' here actually means '/users/'
router.get('/', (req, res) => {
    res.json({ message: "Get all users" });
});

router.post('/', (req, res) => {
    res.json({ message: "Create a new user" });
});

router.get('/:id', (req, res) => {
    res.json({ message: `Get user with ID: ${req.params.id}` });
});

// Export the router so the main app can use it
module.exports = router;

Step 2: Mount the Router in the Main App (app.js)

javascript
const express = require('express');
const userRoutes = require('./routes/userRoutes'); // Import the router

const app = express();

app.use(express.json());

// Mount the router
// Any request starting with '/users' will be handed off to userRoutes
app.use('/users', userRoutes); 

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

By doing this, you instantly clean up your main app.js file. You can create a productRoutes.js, an orderRoutes.js, and so on.


3. The MVC Pattern: Separating Routes and Controllers πŸ§‘β€πŸ³

The Problem

Using express.Router() cleans up our app.js. However, our router files can quickly become bloated. If a route handles data validation, database queries, error handling, and formatting the response, a single route might take up 100 lines of code. Your router file is now the new mess.

The Concept: MVC (Model-View-Controller)

MVC is a software design pattern that separates an application into three interconnected components:

  1. Model: Manages the data, logic, and rules of the application (e.g., interacting with the database).
  2. View: The visual output (UI) the user sees.
  3. Controller: Accepts input, processes it, and converts it into commands for the Model or View.

Industry Note: In modern Express API development (where React, Vue, or Angular handle the frontend), the "View" is mostly ignored on the backend. We focus heavily on Models and Controllers.

How it solves the problem

We separate the "what path was requested" (Router) from the "what actually happens" (Controller).

Imagine you are eating at a restaurant.

  • The Router is the waiter. The waiter takes your order (the request) and carries it to the kitchen.
  • The Controller is the chef. The chef receives the order, gathers ingredients from the fridge (the Model), cooks the food, and gives it back to the waiter to serve.

If the waiter started cooking your meal at your table, the restaurant would be chaos. In code, do not let your Router cook the data. Let it pass the request to a Controller.

Industry Practice: Implementing Controllers

Step 1: Create the Controller (controllers/userController.js)

javascript
// The controller contains the actual business logic
const getAllUsers = (req, res) => {
    // Imagine we are fetching from a database here
    res.status(200).json({ message: "List of all users" });
};

const createUser = (req, res) => {
    const userData = req.body;
    // Logic to save user to DB would go here
    res.status(201).json({ message: "User created", data: userData });
};

module.exports = {
    getAllUsers,
    createUser
};

Step 2: Clean up the Router (routes/userRoutes.js)

javascript
const express = require('express');
const userController = require('../controllers/userController'); 

const router = express.Router();

// The router now only cares about HTTP methods and paths.
// It delegates the actual work to the controller functions.
router.get('/', userController.getAllUsers);
router.post('/', userController.createUser);

module.exports = router;

Now, your router is highly readable. You can look at it and instantly know exactly what routes exist and what functions they trigger.


4. Organizing Your Directory Structure for Scale πŸ“

The Problem

When you split code into modules, routers, and controllers, you suddenly have dozens of files. Without a strict organizational standard, developers will just throw files wherever they want. "Does the database connection go in the controllers folder? Do I put middleware in the routes folder?" This creates a disorganized project that is difficult to navigate.

The Concept: Standard Directory Structure

A directory structure is a formalized hierarchy of folders and files. In Express, there is no strictly enforced folder structure by the framework itself (unlike Angular or Next.js), but the industry has settled on a standardized layout based on roles.

The Solution: Role-Based Architecture

The most common and practical way to structure an Express application is by separating files based on their technical role (Models, Controllers, Routes, Middlewares).

Industry Practice: The Standard Tree

Here is what a professional, production-ready Express API structure looks like:

text
my-express-app/
β”‚
β”œβ”€β”€ controllers/          # Business logic (the "chefs")
β”‚   β”œβ”€β”€ userController.js
β”‚   └── productController.js
β”‚
β”œβ”€β”€ models/               # Database schemas and data logic
β”‚   β”œβ”€β”€ User.js
β”‚   └── Product.js
β”‚
β”œβ”€β”€ routes/               # Express Routers (the "waiters")
β”‚   β”œβ”€β”€ userRoutes.js
β”‚   └── productRoutes.js
β”‚
β”œβ”€β”€ middlewares/          # Custom middleware functions (auth, error handling)
β”‚   β”œβ”€β”€ authMiddleware.js
β”‚   └── errorHandler.js
β”‚
β”œβ”€β”€ config/               # Environment and 3rd party configurations
β”‚   └── database.js       # DB connection logic
β”‚
β”œβ”€β”€ app.js                # Express app setup and middleware mounting
β”œβ”€β”€ server.js             # The entry point that starts the server
└── package.json          

Pro-Tip: Why separate app.js and server.js?

You will notice the industry separates app.js and server.js.

  • app.js configures the Express application, mounts the routes, and handles middleware. It does not call app.listen().
  • server.js imports the app from app.js, connects to the database, and finally calls app.listen() to start the server.

Why? Automated Testing. When you write tests for your API (using tools like Jest and Supertest), you need to import your Express app to test the routes without actually starting the server on a network port. If app.listen() is inside app.js, your tests will throw "Port already in use" errors. Separating them solves this elegantly.

javascript
// server.js
const app = require('./app');
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`πŸš€ Server listening on port ${PORT}`);
});

References & Further Reading

Challenge

Challenge: Refactor a Monolithic Express App

You've been tasked with refactoring a single-file Express application into a scalable, modular structure following industry best practices. The existing code handles API endpoints for products, but all logic is crammed into one file, making it difficult to maintain.

Your goal is to restructure the application logic within the provided commented sections, simulating a multi-file project structure.

Instructions:

  1. Controller Logic (controllers/productController.js):

    • Create and export four functions: getAllProducts, getProductById, createProduct, and updateProduct.
    • Each function should accept (req, res) as arguments and contain the logic to send the appropriate JSON response, similar to the original monolithic code.
  2. Router Configuration (routes/productRoutes.js):

    • Create a new router instance using express.Router().
    • Import the controller functions you defined.
    • Define the routes for the four product endpoints (GET /, GET /:id, POST /, PUT /:id).
    • Connect each route to its corresponding controller function.
    • Export the configured router.
  3. Application Setup (app.js):

    • Create the main Express application instance.
    • Set up the express.json() middleware.
    • Import and mount the product router, ensuring all its routes are prefixed with /api/products.
    • Export the app instance. Do not call app.listen() in this section.
  4. Server Initialization (server.js):

    • Import the app instance from the app.js section.
    • Define a PORT constant.
    • Start the server using app.listen().

Expected result

Your code should be organized into four distinct logical blocks, each fulfilling a specific role in the application architecture.

controllers/productController.js

This block should define and export an object containing four methods:

  • getAllProducts(req, res): Sends a JSON response for retrieving all products.
  • getProductById(req, res): Sends a JSON response for retrieving a single product by its ID from req.params.id.
  • createProduct(req, res): Sends a 201 status and a JSON response for creating a new product.
  • updateProduct(req, res): Sends a JSON response for updating a product by its ID.

routes/productRoutes.js

This section should:

  • Import express and the controller object.
  • Create an express.Router() instance.
  • Define the following routes and link them to the controller methods:
    • router.get('/', productController.getAllProducts)
    • router.post('/', productController.createProduct)
    • router.get('/:id', productController.getProductById)
    • router.put('/:id', productController.updateProduct)
  • Export the router module.

app.js

This block should:

  • Import express and the product router.
  • Create an app instance.
  • Apply the express.json() middleware.
  • Mount the product router using app.use('/api/products', productRoutes).
  • Export the configured app instance.

server.js

This final section should:

  • Import the app from the app.js block.
  • Define a constant for the port number (e.g., const PORT = 3000).
  • Call app.listen() with the port and a callback function to start the server.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.