json-server-reset: Middleware for Data Reset and Merge

1.6.4 · active · verified Tue Apr 21

json-server-reset is a middleware for the popular json-server library, enabling developers to programmatically reset or merge the in-memory database of a running mock API. The current stable version is 1.6.4. Releases are infrequent but consistent, primarily driven by dependency updates and occasional feature additions, as seen with features like 'merge mode' and 'reset module' in v1.5.0 and v1.6.0. Its key differentiator is providing a simple HTTP endpoint (`/reset` or `/merge`) to modify the mock database state during testing or development, which is crucial for maintaining consistent test environments or quickly iterating on frontend changes without restarting the mock server. It integrates directly into the json-server middleware chain, requiring no complex setup beyond standard Express middleware practices. This package is vital for scenarios where a dynamic, resettable mock backend is needed, especially in automated testing suites or rapid prototyping.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up a `json-server` instance with `json-server-reset` middleware, allowing API data to be reset via a POST request to `/reset`.

const jsonServer = require('json-server');
const reset = require('json-server-reset');
const path = require('path');
const fs = require('fs');

const dataFilename = path.join(__dirname, 'data.json');
// Create a simple initial data file if it doesn't exist
if (!fs.existsSync(dataFilename)) {
  fs.writeFileSync(dataFilename, JSON.stringify({ todos: [], users: [{ id: 1, name: 'Alice' }] }, null, 2));
}

const server = jsonServer.create();
const router = jsonServer.router(dataFilename);

// json-server-reset requires body-parser, which is included in jsonServer.defaults
server.use(
  jsonServer.defaults({
    static: '.', // optional static server folder
    bodyParser: true,
    readOnly: false,
  })
);

// Attach the reset middleware before the json-server router
// The middleware expects the router's db to be accessible via server.db
server.use(reset);
server.db = router.db;
server.use(router);

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`JSON Server with reset middleware is running on port ${PORT}`);
  console.log(`Try:`);
  console.log(`- GET http://localhost:${PORT}/todos`);
  console.log(`- POST http://localhost:${PORT}/todos text='New Todo'`);
  console.log(`- POST http://localhost:${PORT}/reset todos:=[] (using httpie)`);
  console.log(`- POST http://localhost:${PORT}/reset users:='[{ "id": 2, "name": "Bob" }]' (using httpie)`);
});

view raw JSON →