1

I created a service in express to send emails, now I'm implementing a middleware for jwt authentication, it is already working, now I would like this middleware to be called automatically for any api I have or the ones I will cre

I tried to do the following assignment on my root, checkToken is my function on middleware

const app = express();
app.use(checkToken, require('./middlewares'))
app.use(`${config.URL_BASE}/email`, require('./apis/email'))
.
.
.

currently to call the middleware i'm doing, its works very well

router.post('', middleware.checkToken, async function (req, res) {
  const {
    type: typeCode,
.
.
.

its works very well, but my other api dont call the middleware, i didn't want to explicitly call again

Other api

router.get('/health', async (req, res) => {
  res.status(200).send({ message: 'Ready.' })
})
GustavoNogueira
  • 389
  • 1
  • 3
  • 16

2 Answers2

3

To have middleware called for all routes, just do an app.use(yourMiddleware) before any of the routes are defined.

To have middleware called for one set of routes, but not other routes, put all the routes you want the middleware to be called for on a particular router that has a path prefix that only matches a subset of your routes. Then execute the middleware on that router before any of its routes are defined.

Here's an example of the 2nd option:

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

// load and configure api router
app.use('/api', require('./apiRouter.js'));

app.listen(...);

Then, inside apiRouter.js:

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

// middleware that is called for all api routes
router.use(myMiddleware);

// define api routes here
router.get('/list', ...)

module.exports = router;
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

router.use() mounts middleware for the routes served by the specific router.

router.use(checkToken)
router.get('/health', getHandler)
router.post('/', postHandler)
module.exports = router
Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38