2

How can I use a middleware ONLY FOR my json-server specific routes? In the json-server docs, I can see the following instructions:

const jsonServerRouter = jsonServer.router('mock-server/db.json')


server.use(customMiddleware)
server.use(jsonServerRouter) // customMiddleware should be executed ONLY FOR this jsonServerRouter

/*
Problem is here, customMiddleware has already been executed,
so following routes will use the middleware too
*/
server.use(otherRoutes)

What I've tried:

// This syntax is similar to the previous code. So it doesnt work
server.use(customMiddleware, jsonServerRouter)
// Passing the middleware to the 'router' function doesnt work
const jsonServerRouter = jsonServer.router('mock-server/db.json', customMiddleware)
Rashomon
  • 5,962
  • 4
  • 29
  • 67
  • then just put it inside `use()`? Like `server.use(customMiddleware, jsonServerRouter)` – bill.gates Apr 18 '22 at 08:58
  • Thats similar to the code in the question. Already tried :( – Rashomon Apr 18 '22 at 08:59
  • in your `customMiddleware`, check `req.path` and then run it if it's the route, else call `next()` – traynor Apr 18 '22 at 09:57
  • @traynor That would be an option... but requires changing the `path` variable if endpoints paths change in the future. A violation of 'dont repeat yourself (DRY)' good practice IMO. But seems like theres not other way :( – Rashomon Apr 18 '22 at 10:16
  • isn't it possible by simply changing the order i.e. define `otherRoutes` first and then register middleware? – manpreet Apr 18 '22 at 10:37

0 Answers0