0
0
Expressframework~5 mins

Controller pattern for route handlers in Express

Choose your learning style9 modes available
Introduction

The controller pattern helps organize your code by separating route logic from business logic. This makes your app easier to read and maintain.

When your Express app has many routes and you want to keep code clean.
When you want to reuse logic across different routes.
When you want to test route logic separately from routing setup.
When you want to keep route files simple and focused on routing only.
Syntax
Express
const controller = {
  methodName: (req, res) => {
    // handle request
    res.send('response');
  }
};

app.get('/route', controller.methodName);

Controllers are usually objects with methods for each route action.

Route files import controllers and assign methods as handlers.

Examples
Example of a controller with two methods for GET and POST routes.
Express
const userController = {
  getUser: (req, res) => {
    res.send('User data');
  },
  createUser: (req, res) => {
    res.send('User created');
  }
};

app.get('/user', userController.getUser);
app.post('/user', userController.createUser);
Simple controller function used directly as route handler.
Express
function getProduct(req, res) {
  res.send('Product info');
}

app.get('/product', getProduct);
Sample Program

This Express app uses a controller object to handle two routes: one to list products and one to show product details by ID.

Express
import express from 'express';
const app = express();

const productController = {
  list: (req, res) => {
    res.send('List of products');
  },
  detail: (req, res) => {
    const id = req.params.id;
    res.send(`Details of product ${id}`);
  }
};

app.get('/products', productController.list);
app.get('/products/:id', productController.detail);

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Controllers keep your route files clean and focused on routing only.

Use descriptive method names in controllers for clarity.

Controllers make testing easier by isolating logic from routing.

Summary

The controller pattern separates route handling logic from routing setup.

It improves code organization and readability.

Controllers help reuse logic and simplify testing.