Socket
Socket
Sign inDemoInstall

json-server

Package Overview
Dependencies
Maintainers
1
Versions
153
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

json-server

> [!IMPORTANT] > Viewing alpha v1 documentation – usable but expect breaking changes. For stable version, see [here](https://github.com/typicode/json-server/tree/v0)


Version published
Weekly downloads
303K
increased by5.91%
Maintainers
1
Weekly downloads
 
Created

What is json-server?

json-server is a full fake REST API with zero coding in less than 30 seconds. It allows you to create a mock REST API using a simple JSON file as the database.

What are json-server's main functionalities?

Create a Fake REST API

This code sets up a basic JSON server that reads from a 'db.json' file and serves it as a REST API. The server listens on port 3000.

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);
server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running');
});

Custom Routes

This code demonstrates how to use custom routes with json-server. The rewriter middleware is used to map custom routes to the default routes.

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);
server.use(jsonServer.rewriter({
  '/api/*': '/$1',
  '/blog/:resource/:id/show': '/:resource/:id'
}));
server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running');
});

Add Custom Middleware

This code adds custom middleware to the JSON server. In this example, a timestamp is added to the request body for POST requests.

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);

server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.body.createdAt = Date.now();
  }
  next();
});

server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running');
});

Other packages similar to json-server

FAQs

Package last updated on 07 Jan 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc