Get a Quote Right Now

Edit Template

Router-level Middleware

Router-level Middleware: Router-level middleware is applied to specific routes using the router.use() method. It is useful for tasks related to specific routes, like authentication or data validation.

Example: Authentication middleware for a specific route

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

// Router-level middleware
const authenticate = (req, res, next) => {
if (req.query.auth === ‘secret’) {
next();
} else {
res.status(401).send(‘Unauthorized’);
}
};

router.use(authenticate);

router.get('/', (req, res) => {
res.send('Authenticated Route');
});

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

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

Share

Leave a Reply

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