Node.js – Express.js Routing

Routing in Express.js refers to the process of defining how an application responds to different client requests — based on the URL path and the HTTP method used (GET, POST, PUT, DELETE, etc.). A route is a combination of a URL pattern and an HTTP method that maps to a specific handler function (called a route handler).

Think of routing like a receptionist at a company — every person who walks in has a request, and the receptionist directs them to the right department based on what they need. Routes work the same way: each incoming request is matched to the right handler based on its URL and method.

Basic Route Syntax

app.METHOD(PATH, HANDLER)
  • METHOD: An HTTP method in lowercase — get, post, put, delete, etc.
  • PATH: The URL path as a string (e.g., '/', '/users', '/about').
  • HANDLER: A function that runs when the route is matched. It receives req and res.

Basic HTTP Method Routes

const express = require('express');
const app = express();

app.use(express.json()); // Middleware to parse JSON request bodies

// GET – retrieve data
app.get('/items', function(req, res) {
  res.json([{ id: 1, name: 'Pen' }, { id: 2, name: 'Notebook' }]);
});

// POST – create new data
app.post('/items', function(req, res) {
  const newItem = req.body;
  console.log("New item received:", newItem);
  res.status(201).json({ message: 'Item created', item: newItem });
});

// PUT – update existing data
app.put('/items/1', function(req, res) {
  const updated = req.body;
  res.json({ message: 'Item updated', item: updated });
});

// DELETE – remove data
app.delete('/items/1', function(req, res) {
  res.json({ message: 'Item deleted' });
});

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

Route Parameters

Route parameters are named segments of the URL preceded by a colon (:). They allow a single route to match multiple similar paths:

app.get('/users/:id', function(req, res) {
  const userId = req.params.id;
  res.json({ message: 'Fetching user with ID: ' + userId });
});

app.get('/posts/:category/:slug', function(req, res) {
  const { category, slug } = req.params;
  res.json({ category, slug });
});

Visiting /users/42 sets req.params.id to '42'.

Visiting /posts/tech/nodejs-guide sets req.params.category to 'tech' and req.params.slug to 'nodejs-guide'.

Query Parameters

Query parameters are key-value pairs that appear in the URL after a ?. They are accessed via req.query:

// Example URL: /search?keyword=node&page=2&limit=10

app.get('/search', function(req, res) {
  const { keyword, page, limit } = req.query;

  res.json({
    searching_for: keyword,
    page: page || 1,
    limit: limit || 10
  });
});

Express Router – Organizing Routes into Separate Files

As an application grows, putting all routes in app.js becomes messy. The express.Router() class allows routes to be split into separate files by feature.

Creating a Router File

// routes/users.js

const express = require('express');
const router = express.Router();

// GET all users
router.get('/', function(req, res) {
  res.json([
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]);
});

// GET a single user by ID
router.get('/:id', function(req, res) {
  res.json({ id: req.params.id, name: 'Alice' });
});

// POST – create a new user
router.post('/', function(req, res) {
  const newUser = req.body;
  res.status(201).json({ message: 'User created', user: newUser });
});

// DELETE a user
router.delete('/:id', function(req, res) {
  res.json({ message: 'User ' + req.params.id + ' deleted' });
});

module.exports = router;

Using the Router in app.js

// app.js

const express = require('express');
const app = express();

app.use(express.json());

// Mount the users router at /users
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);

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

All routes in the users.js file are now accessible under the /users prefix. For example:

  • GET /users → gets all users
  • GET /users/5 → gets user with ID 5
  • POST /users → creates a new user
  • DELETE /users/5 → deletes user with ID 5

Organized Project Structure with Multiple Routers

my-express-app/
├── app.js
├── routes/
│   ├── users.js
│   ├── products.js
│   └── orders.js
└── package.json
// app.js

const express = require('express');
const app = express();

app.use(express.json());

app.use('/users',    require('./routes/users'));
app.use('/products', require('./routes/products'));
app.use('/orders',   require('./routes/orders'));

app.listen(3000);

app.all() – Matching Any HTTP Method

app.all() matches any HTTP method for a given path. It is often used for logging or applying logic before any route handler:

app.all('/admin/*', function(req, res, next) {
  console.log("Admin route accessed:", req.method, req.url);
  next(); // Pass to the next matching route
});

Route Chaining with app.route()

Multiple HTTP methods for the same path can be chained together cleanly:

app.route('/books')
  .get(function(req, res) {
    res.send('Get all books');
  })
  .post(function(req, res) {
    res.send('Add a new book');
  });

app.route('/books/:id')
  .get(function(req, res) {
    res.send('Get book ' + req.params.id);
  })
  .put(function(req, res) {
    res.send('Update book ' + req.params.id);
  })
  .delete(function(req, res) {
    res.send('Delete book ' + req.params.id);
  });

Key Points

  • A route in Express connects a URL path and HTTP method to a handler function.
  • Route parameters (:paramName) allow a single route to handle dynamic URL values via req.params.
  • Query parameters appear after ? in the URL and are accessed via req.query.
  • express.Router() allows routes to be organized into separate files for better maintainability.
  • Routers are mounted in app.js using app.use('/prefix', router).
  • app.route() enables chaining multiple HTTP methods for the same path cleanly.
  • Separating routes into files by feature (users, products, orders) is a best practice for larger applications.

Leave a Comment

Your email address will not be published. Required fields are marked *