Search code examples
javascriptnode.jsexpressmiddlewarejson-server

json-server add read-only route with middleware


In my json-server setup I'd like to set a read-only route.

So instead of setting that route in the db.json file, I'm using a middleware (named middleware.js):

module.exports = (req, res, next) => {
  if (req.url === '/authenticate') {
    res.body = {
      some_property: "some_value"
    };
    console.log("triggered!!!");
  }
  next();
};

so I run it giving:

json-server --watch db.json --middlewares middleware.js

the problem is that, despite the if block is triggered and I can see the console.log message, the body of the response will always be empty.


Solution

  • I solved my issue using:

    module.exports = (req, res, next) => {
      if (req.url === '/authenticate') {
        res.send({
          some_property: "some_value"
        });
      } else {
        next();
      }
    };