How to apply JWT middleware?
To apply JWT middleware, you need to use the app.use or router.use method of the Express framework, and pass the jwtMiddleware function as an argument. You can apply the middleware globally, to all the routes, or locally, to specific routes. For example, to apply the middleware globally, you can use the following code:
<code>const express = require('express');
const jwtMiddleware = require('./jwtMiddleware');
// apply the middleware to all the routes
app.get('/profile', (req, res) => {
// access the user data from the request object
res.send(`Hello, ${req.user.userId}! You are a ${req.user.role}.`);
app.get('/secret', (req, res) => {
// check the user role from the request object
if (req.user.role === 'admin') {
res.send('You have access to the secret data.');
res.send('You are not authorized to see the secret data.');
console.log('Server running on port 3000');
To apply the middleware locally, you can use the following code:
<code>const express = require('express');
const jwtMiddleware = require('./jwtMiddleware');
app.get('/profile', (req, res) => {
// no middleware applied, anyone can access this route
res.send('This is your public profile.');
app.get('/secret', jwtMiddleware, (req, res) => {
// middleware applied, only users with valid tokens can access this route
res.send('This is your secret data.');
console.log('Server running on port 3000');