Expressjs Routing And Middleware Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Expressjs Routing and Middleware

Express.js Routing and Middleware: A Detailed Guide

Express.js Routing

Important Information:

  • HTTP Methods: Express supports all common HTTP methods such as GET, POST, PUT, DELETE, etc.
  • Route Paths: You can define routes using strings, string patterns, or regular expressions.
  • Route Handlers: These are functions that execute when a route is matched. Handlers can be single functions, arrays of functions, or combinations.

Here’s how you can set up basic routes in Express:

Basic Example:

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

// Basic routing example
app.get('/', function(req, res) {
  res.send('Hello World!');
});

app.post('/submit-form', function(req, res) {
  res.send('Form submitted successfully!');
});

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

Route Parameters: Route parameters allow you to capture segments of the request URL and use them as part of your request handling logic. For example:

app.get('/users/:userId/books/:bookId', function(req, res) {
  res.send(`Requested user ID: ${req.params.userId}, Book ID: ${req.params.bookId}`);
});

Query Strings vs Route Parameters:

  • Route Parameters are part of the URL path (e.g., /users/1).
  • Query Strings are part of the URL query section after ?, separated by & (e.g., /users?id=1&name=john).

Advanced Route Patterns: You can specify more complex route patterns or use regular expressions:

app.get('/users/:userId([0-9]+)', function(req, res) {
  // This handler will match if userId is one or more digits
  res.send(`User ${req.params.userId}`);
});

app.get(/.*fly$/, function(req, res) {
  // Regex example that routes paths ending with 'fly'
  res.send('Ending with fly');
});

Router Objects: Express allows you to create modular, mountable route handlers using the express.Router class:

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

// Route middleware specific to this router
router.use(function(req, res, next) {
  console.log('Time:', Date.now());
  next();
});

// Define the home page route
router.get('/', function(req, res) {
  res.send('Wiki home page');
});

// Define the about page route
router.get('/about', function(req, res) {
  res.send('About this wiki');
});

module.exports = router;

Express.js Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function in the stack.

Important Information:

  • Application-level Middleware: Binds with app.use() or app.METHOD(), where METHOD is the method of the HTTP request (e.g., app.post()).
  • Router-level Middleware: Similar to application-level but bound to an instance of express.Router().
  • Error-handling Middleware: Designed to log errors and send responses to clients.
  • Built-in Middleware: Provides various functionalities, most notably express.json() and express.urlencoded().
  • Third-party Middleware: Can be installed via npm and provides extended functionality like helmet, compression, etc.

Basic Middleware Example:

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

// Basic logging middleware
function logger(req, res, next) {
  console.log(`${req.method} ${req.url} - ${Date.now()}`);
  next(); // Passes control to the next middleware
}

// Use the logger middleware for all routes
app.use(logger);

app.get('/', function(req, res) {
  res.send('Hello World!');
});

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

Multiple Middleware Functions: You can apply multiple middleware functions at the same time:

app.use(['/a', '/b'], function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function(req, res, next) {
  console.log('Time:', Date.now());
  next();
});

Router-specific Middleware:

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

router.use(function(req, res, next) {
  console.log('Time:', Date.now());
  next();
});

router.get('/', function(req, res) {
  res.send('Birds home page');
});

router.get('/about', function(req, res) {
  res.send('About birds');
});

app.use('/birds', router);

Error-handling Middleware:

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Order of Middleware: The order in which middleware is defined is significant because it defines the order in which middleware functions are executed. For example:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Expressjs Routing and Middleware

Step 1: Setting Up the Project

  1. Initialize a new Node.js project:

    mkdir express-app
    cd express-app
    npm init -y
    
  2. Install Express.js:

    npm install express
    

Step 2: Setting Up the Basic Server

Create a file named server.js and set up a basic Express server.

// server.js

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

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Step 3: Creating Basic Routes

Let's add some basic routes to handle HTTP requests.

// server.js (continued)

// Home Route
app.get('/', (req, res) => {
    res.send('Welcome to the Home Page!');
});

// About Route
app.get('/about', (req, res) => {
    res.send('This is the About Page');
});

// 404 Route (Catch-all)
app.use((req, res) => {
    res.status(404).send('Page not found');
});

Step 4: Implementing Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.

  1. Logging Middleware: Create middleware to log each request.

    // server.js (continued)
    
    // Logging Middleware
    const logger = (req, res, next) => {
        console.log(`${req.method} request for '${req.url}' - ${new Date()}`);
        next(); // Move to the next middleware or route handler
    };
    
    // Use the logger middleware
    app.use(logger);
    
  2. Custom Header Middleware: Add a custom header to all outgoing responses.

    // server.js (continued)
    
    // Custom Header Middleware
    const addCustomHeader = (req, res, next) => {
        res.setHeader('X-Powered-By', 'ExpressJS');
        next(); // Move to the next middleware or route handler
    };
    
    // Use the custom header middleware
    app.use(addCustomHeader);
    

Step 5: Adding POST Routes with Body Parsing

To handle POST requests, you'll need middleware to parse the request body. Express provides express.json() and express.urlencoded() for this purpose.

  1. Body Parsing Middleware:

    // server.js (continued)
    
    // Body Parsing Middleware
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    
    // POST Route
    app.post('/data', (req, res) => {
        const data = req.body;
        res.send(`Received data: ${JSON.stringify(data)}`);
    });
    

Step 6: Handling Static Files

Serve static files like HTML, CSS, and JavaScript using Express.

  1. Static Files Middleware:

    // server.js (continued)
    
    // Serve static files from the "public" directory
    app.use(express.static('public'));
    
    // Create a folder named "public" in the same directory as server.js
    // and add an "index.html" file inside it
    

Complete Code

Here's the complete server.js file after all the steps:

// server.js

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

// Logging Middleware
const logger = (req, res, next) => {
    console.log(`${req.method} request for '${req.url}' - ${new Date()}`);
    next();
};

// Custom Header Middleware
const addCustomHeader = (req, res, next) => {
    res.setHeader('X-Powered-By', 'ExpressJS');
    next();
};

// Body Parsing Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Use the logger middleware
app.use(logger);

// Use the custom header middleware
app.use(addCustomHeader);

// Serve static files from the "public" directory
app.use(express.static('public'));

// Home Route
app.get('/', (req, res) => {
    res.send('Welcome to the Home Page!');
});

// About Route
app.get('/about', (req, res) => {
    res.send('This is the About Page');
});

// POST Route
app.post('/data', (req, res) => {
    const data = req.body;
    res.send(`Received data: ${JSON.stringify(data)}`);
});

// 404 Route (Catch-all)
app.use((req, res) => {
    res.status(404).send('Page not found');
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Running the Application

  1. Create a public folder and add an index.html file inside it for testing static file serving.

  2. Start the server:

    node server.js
    
  3. Test the application:

    • Open your browser and visit http://localhost:3000/ to see the home page.
    • Visit http://localhost:3000/about to see the about page.
    • Visit http://localhost:3000/nonexistent to see the 404 error page.
    • Use a tool like Postman to send a POST request to http://localhost:3000/data with JSON body to test the POST route.
    • Visit http://localhost:3000/index.html to see the static HTML file.

Top 10 Interview Questions & Answers on Expressjs Routing and Middleware

Top 10 Questions and Answers on Express.js Routing and Middleware

1. What is Express.js routing?

2. How do you create a basic route in Express.js?

Answer: Creating a basic route in Express involves defining a method on the Express app object or router that specifies the URL pattern and the handler function to execute when the request matches the pattern and method. Here’s a simple example:

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

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(3000);

In this example, app.get() creates a route that responds with 'Hello World!' when a GET request is made to the root URL (/).

3. Can routes be defined using regular expressions?

Answer: Yes, routes in Express can also be defined using regular expressions. This allows for more flexible URL patterns, useful when you need to handle dynamic segments or other complex path structures. For example:

app.get(/^\/hello\/(\w+)$/, (req, res) => {
    const name = req.params[0];
    res.send(`Hello ${name}!`);
});

This route matches any URL that starts with /hello/ followed by a word character sequence and captures it into req.params[0].

4. What is Middleware in Express.js?

Answer: Middleware in Express.js are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function in the stack. Middleware are key components for building web applications as they help with tasks such as parsing bodies, setting headers, logging requests, authentication, error handling, and much more.

5. How do you use custom middleware in Express.js?

Answer: To add a custom middleware in Express, simply define a function that takes in the request (req), response (res), and next callback parameters, then register it using app.use() or directly in the route:

function myMiddleware(req, res, next) {
    console.log('Request received');
    next(); // Call next to pass control to the next middleware function
}

app.use(myMiddleware);

// Or in a specific route
app.get('/', myMiddleware, (req, res) => {
    res.send('Hello World!');
});

6. What are some built-in middlewares provided by Express.js?

Answer: Express has several built-in middleware modules:

  • express.json(): Parses JSON bodies.
  • express.urlencoded(): Parses URL-encoded bodies (key-value pairs), often used when submitting forms.
  • express.static(): Serves static files from a specified directory.
  • express.Router(): Facilitates route modularization.

Example:

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

app.use(express.json()); // For parsing JSON bodies
app.use(express.static('public')); // Serve static files from 'public' dir

7. How do you chain multiple middleware functions in a route in Express.js?

Answer: In Express, you can chain multiple middleware functions in a single route by passing them as arguments before the final handler function. Middleware functions must call next() to pass control to the next middleware in the chain.

function checkAuth(req, res, next) {
    if (req.isAuthenticated()) return next();
    res.status(403).send('Access Denied');
}

function logRequest(req, res, next) {
    console.log('Request logged');
    next();
}

app.get('/profile', checkAuth, logRequest, (req, res) => {
    res.send('Profile Page');
});

Here, checkAuth first checks if the user is authenticated, and if so, calls logRequest, which logs the request and passes control to the final route handler.

8. What are third-party middlewares, and how do you use them?

Answer: Third-party middlewares are modules created by the community that you install via npm and integrate into your Express app to add specific functionalities like database connection management (mongoose), cookie parsing (cookie-parser), error handling (helmet), etc. Here’s an example of using body-parser for parsing JSON requests:

npm install body-parser

Then in your app:

const bodyParser = require('body-parser');

app.use(bodyParser.json());

However, note that starting from Express 4.16, you don’t need body-parser anymore as most of its features were incorporated into Express itself.

9. How does the Error Handling Middleware work in Express.js?

Answer: Error-handling middleware follow the same signature as the other middlewares except they take four arguments instead of three, specifically (err, req, res, next). They can catch errors thrown in any synchronous or asynchronous middleware or route handlers, allowing for centralized error management. Example:

function errorHandler(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something broke!');
}

app.use(errorHandler);

You can throw errors using next(new Error(...)) anywhere in your route handlers or middleware to trigger the error handler.

10. Can you explain the purpose of the next function in middleware?

Answer: The next parameter in middleware functions is a callback function that tells Express to move to the next middleware function. If next() is called without any arguments, the remaining middleware functions will be executed in order based on the stack position. However, next(err) triggers the error handling middleware, bypassing all other remaining non-error handling middleware.

In summary, next() serves as a controller for the flow of middleware execution, allowing developers to perform tasks sequentially or jump directly to an error handler.

You May Like This Related .NET Topic

Login to post a comment.