json-server
                                
                                 json-server copied to clipboard
                                
                                    json-server copied to clipboard
                            
                            
                            
                        feat: add middleware
Closes #1581 #1520 #1497 #1177
awaiting #1625 you can preview by adding this to your package.json:
"scripts": {
    "server": "node node_modules/json-server/lib/bin.js db.json --port 3000 --middleware=logger.mjs",
    "postinstall": "cd node_modules && git clone -b feature/add-middleware https://github.com/rkristelijn/json-server.git"
  }
and create a logger.mjs file:
// logger.mjs
import chalk from 'chalk';
export default (req, _res, next) => {
 const currentDate = new Date().toISOString();
 console.log(chalk.green(req.method), chalk.yellow(req.url), chalk.blue(`${currentDate}`));
 // Check if the request body is already parsed
 if (req.body && Object.keys(req.body).length > 0) {
   console.log(chalk.magenta('Body:'), req.body);
 } else {
   // Manually parse the request body if not already parsed
   let body = '';
   req.on('data', (chunk) => {
     body += chunk.toString();
   });
   req.on('end', () => {
     if (body) {
       try {
         const parsedBody = JSON.parse(body);
         console.log(chalk.magenta('Body:'), parsedBody);
       } catch (error) {
         console.log(chalk.red('Failed to parse body'), error);
       }
     }
     next();
   });
   return;
 }
 next();
};
it will output:
> node node_modules/json-server/lib/bin.js db.json --port 3000 --middleware=src/utils/logger.mjs
Loading middleware from src/utils/logger.mjs
app.ts: Using middleware [Function: default]
JSON Server started on PORT :3000
Press CTRL-C to stop
Watching db.json...
(˶ᵔ ᵕ ᵔ˶)
Index:
http://localhost:3000/
Static files:
Serving ./public directory if it exists
Endpoints:
http://localhost:3000/users
http://localhost:3000/users_columns
[2025-01-03T08:35:43.824Z] POST /posts
Body: { title: 'foo', body: 'bar', userId: 1 }
[2025-01-03T08:35:46.331Z] PATCH /posts/1
Body: { title: 'foo', body: 'bar', userId: 1 }
[2025-01-03T08:35:47.579Z] GET /posts
for these http calls
// test.http
// use https://marketplace.visualstudio.com/items?itemName=humao.rest-client to call
###
GET http://localhost:3000/posts
###
POST http://localhost:3000/posts
Content-Type: application/json
{
  "title": "foo",
  "body": "bar",
  "userId": 1
}
###
PATCH http://localhost:3000/posts/1
Content-Type: application/json
{
  "title": "foo",
  "body": "bar",
  "userId": 1
}