Router-level Middleware in an Express Js

  • Let's create a complete example of a router-level middleware in an Express.js application. In this example, we'll create a router-level middleware that checks for authentication before allowing access to certain routes.
  • Project Structure: Create a project structure with the following directories and files:

    - my-express-app/
        - middlewares/
            - authenticationMiddleware.js
        - routes/
            - index.js
            - admin.js
        - app.js
        - package.json

  • Middleware File (`authenticationMiddleware.js`): Create a router-level middleware that simulates authentication by checking for a token in the request header:

    // middlewares/authenticationMiddleware.js

    const authenticationMiddleware = (req, res, next) => {
        const authToken = req.header('Authorization');

        if (!authToken || authToken !== 'mySecretToken') {
            return res.status(401).send('Unauthorized. Please provide a valid token.');
        }

        next(); // Call the next middleware in the stack
    };

    module.exports = authenticationMiddleware;

  • Route Files (`index.js` and `admin.js`): Create two route files in the `routes` directory:

    // routes/index.js

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

    router.get('/', (req, res) => {
        res.send('Hello from the index route!');
    });

    module.exports = router;



    // routes/admin.js

    const express = require('express');
    const router = express.Router();
    const authenticationMiddleware = require('../middlewares/authenticationMiddleware');

    // Apply the router-level middleware only to the '/admin' route
    router.use(authenticationMiddleware);

    router.get('/dashboard', (req, res) => {
        res.send('Welcome to the Admin Dashboard!');
    });

    module.exports = router;

  • Express App (`app.js`): Set up the Express.js application and use the router-level middleware:

    // app.js

    const express = require('express');
    const authenticationMiddleware = require('./middlewares/authenticationMiddleware');
    const indexRoute = require('./routes/index');
    const adminRoute = require('./routes/admin');

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

    // Use the router-level middleware only for the '/admin' route
    app.use('/admin', authenticationMiddleware);

    // Use the index and admin routes
    app.use('/', indexRoute);
    app.use('/admin', adminRoute);

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

  • Run the Application: Run your application using the command:

    node app.js

  • Visit `http://localhost:3000` in your browser to access the index route, and you should see the message "Hello from the index route!".
  • Visit `http://localhost:3000/admin/dashboard` to access the admin route. Since the router-level middleware (`authenticationMiddleware`) is applied only to the `/admin` route, it will check for the authorization token. If the token is missing or incorrect, it will return a 401 Unauthorized response. If the token is valid, it will allow access to the admin dashboard route.
  • This example demonstrates the use of a router-level middleware (`authenticationMiddleware`) in an Express.js application. The middleware is applied only to specific routes, allowing for targeted authentication checks.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...