Routing in Express.js: Handling User Requests

In Express.js, routing is a crucial concept that allows you to define how your application handles incoming HTTP requests from users. Routes enable you to specify specific actions when users send requests to specific URLs on your application.

Step 1: Creating a Basic Route

To create a route in Express.js, you use the app.METHOD(PATH, HANDLER) method of the application object (app) to register a route for a specific HTTP method METHOD and a path PATH. The HANDLER is a handler function that will be called when a request hits that route.

For example, to create a route that handles a GET request to /hello, you can use the following code:

app.get('/hello', (req, res) => {
  res.send('Hello, this is the /hello route!');

Step 2: Handling Requests and Responses

In the handler function, you can handle incoming requests from users and respond by using the req (request) and res (response) objects. The req object contains information about the incoming request, such as URL parameters, sent data, the sender's IP address, etc. The res object contains methods to respond to the request, such as res.send(), res.json(), res.render(), etc.

Step 3: Handling Multiple Routes

Express.js allows you to define multiple routes for the same URL with different HTTP methods. For example:

app.get('/hello', (req, res) => {
  res.send('Hello, this is the GET /hello route!');
});'/hello', (req, res) => {
  res.send('Hello, this is the POST /hello route!');

Step 4: Handling Dynamic Parameters

You can also define routes that contain dynamic parameters, defined by a colon (:). For example:

app.get('/users/:id', (req, res) => {
  const userId =;
  res.send(`Hello, this is the GET /users/${userId} route!`);

When a user makes a request to /users/123, the userId variable will have the value "123".

Step 5: Separate Routing with Modules

In larger projects, you may want to separate routes into separate files to keep your source code organized and manageable. You can use module.exports to define routes in separate files and then import them into the main file. For example:

// routes/users.js
const express = require('express');
const router = express.Router();

router.get('/profile', (req, res) => {
  res.send('This is the /profile route in users.js!');

module.exports = router;
// app.js
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);

Step 6: Handling Non-existent Routes

Finally, if a user requests a non-existent route, you can define a 404 route to handle it. This is done by setting a default route at the end of your main file:

app.use((req, res, next) => {
  res.status(404).send('Route not found!');

We have learned how to create and handle routes in Express.js. By using this feature, you can customize and handle user requests flexibly and powerfully, making your application more adaptable and scalable. Keep exploring and utilizing routes in building rich and fantastic web applications!