Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vite-plugin-simple-json-server

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vite-plugin-simple-json-server

Provide a file-based mock API for Vite in dev mode

  • 0.6.1
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Help Ukraine now!

vite-plugin-simple-json-server

Provide a file-based mock API for Vite in dev mode.

Release License: MIT


Why vite-plugin-simple-json-server?

This plugin is for lazy developers to create a mock API quickly. Simply place some json files into the mock folder and your file based API is ready. Out of the box you have pagination, sorting, filter and basic CRUD operations.

Additionally the plugin serves static files such as html, js, css, txt.

As well you can define the custom route's handlers in the plugin config.

As bonus, you can visualize the OpenAPI Specification schema generated by the plugin in an interactive UI (Swagger) with zero efforts.

The plugin is lightweight and has only a few dependencies.


Installation

First, install the vite-plugin-simple-json-server package using your package manager.

# Using NPM
npm add -D vite-plugin-simple-json-server

# Using Yarn
yarn add -D vite-plugin-simple-json-server

# Using PNPM
pnpm add -D vite-plugin-simple-json-server

Then, apply this plugin to your vite.config.* file using the plugins property:

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  // ...
  plugins: [jsonServer()],
};

Then, restart the dev server.

This configuration assumes that all json files are in the mock folder under Vite root.

To work correctly, the plugin requires Node version 15.7.0 or higher.

Usage

The vite-plugin-simple-json-server injects own middleware into development and preview servers. By default it is invoked only for serve mode.

The plugin first serves the handler routes, then the json API and at the very end, the static files.

Any query parameters are ignored for static files.

Pagination and count is only available for array-based json. For sorting and filtering the json must be an array of objects.

If there is a parameter in the filter or sort request that is not among the json fields, that parameter will be ignored.

Let's have the products.json in the mock folder.

[
  {
    "id": 1,
    "name": "Banana",
    "price": 2,
    "weight": 1,
    "packing": {
      "type": "box",
    }
  },
  {
    "id": 2,
    "name": "Apple",
    "price": 2,
    "weight": 1,
    "packing": {
      "type": "box",
    }
  },
  {
    "id": 3,
    "name": "Potato",
    "price": 2,
    "weight": 10,
    "packing": {
      "type": "bag",
    }
  },

  ...

]

Pagination

Default limit is 10.

curl http://localhost:5173/products?offset=0


curl http://localhost:5173/products?offset=20

For the custom limit, pass it to the query:

curl http://localhost:5173/products?offset=200&limit=100

The server sets the Link response header with URLs for the first, previous, next and last pages according to the current limit. Also it sets the X-Total-Count header.

Sorting

Default sort order is ascending.

curl http://localhost:5173/products?sort=name

For the descending order prefix a field name with -:

curl http://localhost:5173/products?sort=-name

Multiply field sorting is supported.

curl http://localhost:5173/products?sort=name,-price

Use . to access deep properties.

curl http://localhost:5173/products?sort=packing.type

Filtering

curl  http://localhost:5173/products?id=2


curl  http://localhost:5173/products?id=2&id=3


curl  http://localhost:5173/products?price=2&weight=1

If the requested resource has an id property, you can append the id value to the URL.

curl  http://localhost:5173/products/2

Deep properties

Use . to access deep properties.


curl  http://localhost:5173/products?packing.type=box
Operators

The plugin supports ne, lt, gt, lte, gte and like operators.


curl  http://localhost:5173/products?id[ne]=2

curl  http://localhost:5173/products?id[gt]=1&id[lt]=10


Like is performed via RegExp.


curl  http://localhost:5173/products?name[like]=ota

Count

The count will be returned in the response header X-Total-Count.

curl -I http://localhost:5173/products

You can filter as well while count.

curl -I http://localhost:5173/products?price=2

:bulb: The pagination is available with sort and filter.

CRUD

Full CRUD operations are only available for array-like JSON with a numeric id property.

Array-like

HTTP VerbCRUDEntire Collection (e.g. /products)Specific Item (e.g. /products/{id})
HEADRead204 (OK), items count in X-Total-Count header.405 (Method Not Allowed)
GETRead200 (OK), list of items.
Use pagination, sorting and filtering to navigate large lists.
  • 200 (OK), single item.
  • 404 (Not Found), if ID not found.
POSTCreate
  • 201 (Created), created item, Location header with link to /products/{id} containing new ID.
  • 409 (Conflict) if resource already exists.
  • 400 (Bad Request) for empty body, not valid JSON or too big body (>1e6)
405 (Method Not Allowed).
PUTUpdate/Replace405 (Method Not Allowed).
  • 200 (OK), replaced item.
  • 404 (Not Found), if ID not found.
  • 400 (Bad Request) for empty body, not valid JSON or too big body (>1e6)
PATCHUpdate/Modify405 (Method Not Allowed).
  • 200 (OK), modified item.
  • 404 (Not Found), if ID not found.
  • 400 (Bad Request) for empty body, not valid JSON or too big body (>1e6)
DELETEDelete405 (Method Not Allowed).
  • 200 (OK), empty object {}.
  • 404 (Not Found), if ID not found.

Object

HTTP VerbCRUDEntire Object (e.g. /profile)Specific Item (e.g. /profile/{id})
GETRead200 (OK), object.404 (Not Found).
POSTCreate
  • 201 (Created), replaced object, Location header with link to /profile.
  • 400 (Bad Request) for empty body, not valid JSON or too big body (>1e6)
404 (Not Found).
PUTUpdate/Replace200 (OK), replaced object.404 (Not Found).
PATCHUpdate/Modify200 (OK), modified object.404 (Not Found).
DELETEDelete405 (Method Not Allowed).404 (Not Found).

OpenAPI (Swagger)

The plugin generates JSON according to the OpenAPI Specification v3.0.

It is available on /{api}/v3/openapi.json route.

Also you can explore your API directly on /{api}/v3/openapi page (Swagger UI).

To perform CRUD operations, the plugin assumes that each array-like JSON has a numeric id property.

Configuration

To configure this plugin, pass an object to the jsonServer() function call in vite.config.ts.

vite.config.ts

...
export default defineConfig({
  plugins: [jsonServer({
    handlers: ...
  })]
});
disable
TypeRequiredDefault value
BooleanNofalse

If true the plugin won't run its middleware while dev or preview.

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  plugins: [
    jsonServer({
      disable: true,
    }),
  ],
};
mockDir
TypeRequiredDefault value
StringNomock

It's a subfolder under the Vite root. Place all your JSON files here.

If the file name is index.* then its route will be the parent directory path.

TypeSupported methods
json (object)GET
json (array-like)GET, POST, PUT, PATCH, DELETE
html | htm | shtmlGET
js | mjsGET
cssGET
txt | textGET

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {

  plugins: [
    jsonServer({
      mockDir: 'json-mock-api',
    }),
  ],
};
staticDir
TypeRequiredDefault value
StringNooptions.mockDir

It's a subfolder under the Vite root. An alternative to the mockDir folder for static files such as html, css and js.

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {

  plugins: [
    jsonServer({
      staticDir: 'public',
    }),
  ],
};
urlPrefixes
TypeRequiredDefault value
String[]No[ '/api/' ]

Array of non empty strings.

The plugin will look for requests starting with these prefixes.

Slashes are not obligatory: plugin will add them automatically during option validation.

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  plugins: [
    jsonServer({
      urlPrefixes: [ 
        '/fist-api/', 
        '/second-api/',
      ],
    }),
  ],
};
noHandlerResponse404
TypeRequiredDefault value
BooleanNotrue

If its value is false the server won't respond with 404 error.

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  plugins: [
    jsonServer({
      noHandlerResponse404: false,
    }),
  ],
};
logLevel
TypeRequiredDefault value
LogLevelNoinfo

Available values: 'info' | 'warn' | 'error' | 'silent';

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  plugins: [
    jsonServer({
      logLevel: 'error',
    }),
  ],
};
handlers
TypeRequiredDefault value
MockHandler[]Noundefined

For the custom routes. Array of mock handlers.

The MockHandler type consists of pattern, method, handle and description fields.

pattern

String, required.

Apache Ant-style path pattern. It's done with @howiefh/ant-path-matcher.

The mapping matches URLs using the following rules:

  • ? matches one character;
  • * matches zero or more characters;
  • ** matches zero or more directories in a path;
  • {spring:[a-z]+} matches the regexp [a-z]+ as a path variable named spring.

method

String, optional.

Any HTTP method: GET | POST etc;

MockFunction: (req: Connect.IncomingMessage, res: ServerResponse, urlVars?: Record<string, string>): void

  • req: Connect.IncomingMessage from Vite;
  • res: ServerResponse from Node http;
  • urlVars: key-value pairs from parsed URL.

handle

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  plugins: [
    jsonServer({
      handlers: [
        {
          pattern: '/api/hello/1',
          handle: (req, res) => {
            res.end(`Hello world! ${req.url}`);
          },
        },
        {
          pattern: '/api/hello/*',
          handle: (req, res) => {
            res.end(`Hello world! ${req.url}`);
          },
        },
        {
          pattern: '/api/users/{userId}',
          method: 'POST',
          handle: (req, res, urlVars) => {
            const data = [
              {
                url: req.url,
                urlVars
              },
            ];
            res.setHeader('content-type', 'application/json');
            res.end(JSON.stringify(data));
          },
        },
      ],
    }),
  ],
};

:exclamation: Handlers are served first. They intercept namesake file routes.

limit
TypeRequiredDefault value
NumberNo10

Number of items to return while paging.

Usage:

curl http://localhost:5173/products?offset=300&limit=100

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  plugins: [
    jsonServer({
      limit: 100,
    }),
  ],
};
delay
TypeRequiredDefault value
NumberNo0

Add delay to responses (ms).

vite.config.ts

import jsonServer from 'vite-plugin-simple-json-server';

export default {
  plugins: [
    jsonServer({
      delay: 1000,
    }),
  ],
};

Examples

ExampleSourcePlayground
basicGitHubPlay Online
CRUDGitHubPlay Online

Contributing

You're welcome to submit an issue or PR!

Changelog

See CHANGELOG.md for a history of changes to this plugin.

Inspirations

Keywords

FAQs

Package last updated on 27 Sep 2022

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