Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
vite-plugin-simple-json-server
Advanced tools
Provide a file-based mock API for Vite in dev mode.
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.
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.
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",
}
},
...
]
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.
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
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
Use .
to access deep properties.
curl http://localhost:5173/products?packing.type=box
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
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.
Full CRUD operations are only available for array-like JSON with a numeric id
property.
HTTP Verb | CRUD | Entire Collection (e.g. /products ) | Specific Item (e.g. /products/{id} ) |
---|---|---|---|
HEAD | Read | 204 (OK), items count in X-Total-Count header. | 405 (Method Not Allowed) |
GET | Read | 200 (OK), list of items. Use pagination, sorting and filtering to navigate large lists. |
|
POST | Create |
| 405 (Method Not Allowed). |
PUT | Update/Replace | 405 (Method Not Allowed). |
|
PATCH | Update/Modify | 405 (Method Not Allowed). |
|
DELETE | Delete | 405 (Method Not Allowed). |
|
HTTP Verb | CRUD | Entire Object (e.g. /profile ) | Specific Item (e.g. /profile/{id} ) |
---|---|---|---|
GET | Read | 200 (OK), object. | 404 (Not Found). |
POST | Create |
| 404 (Not Found). |
PUT | Update/Replace | 200 (OK), replaced object. | 404 (Not Found). |
PATCH | Update/Modify | 200 (OK), modified object. | 404 (Not Found). |
DELETE | Delete | 405 (Method Not Allowed). | 404 (Not Found). |
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.
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: ...
})]
});
Type | Required | Default value |
---|---|---|
Boolean | No | false |
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,
}),
],
};
Type | Required | Default value |
---|---|---|
String | No | mock |
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.
Type | Supported methods |
---|---|
json (object) | GET |
json (array-like) | GET , POST , PUT , PATCH , DELETE |
html | htm | shtml | GET |
js | mjs | GET |
css | GET |
txt | text | GET |
vite.config.ts
import jsonServer from 'vite-plugin-simple-json-server';
export default {
plugins: [
jsonServer({
mockDir: 'json-mock-api',
}),
],
};
Type | Required | Default value |
---|---|---|
String | No | options.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',
}),
],
};
Type | Required | Default 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/',
],
}),
],
};
Type | Required | Default value |
---|---|---|
Boolean | No | true |
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,
}),
],
};
Type | Required | Default value |
---|---|---|
LogLevel | No | info |
Available values: 'info' | 'warn' | 'error' | 'silent'
;
vite.config.ts
import jsonServer from 'vite-plugin-simple-json-server';
export default {
plugins: [
jsonServer({
logLevel: 'error',
}),
],
};
Type | Required | Default value |
---|---|---|
MockHandler[] | No | undefined |
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.
Type | Required | Default value |
---|---|---|
Number | No | 10 |
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,
}),
],
};
Type | Required | Default value |
---|---|---|
Number | No | 0 |
Add delay to responses (ms).
vite.config.ts
import jsonServer from 'vite-plugin-simple-json-server';
export default {
plugins: [
jsonServer({
delay: 1000,
}),
],
};
Example | Source | Playground |
---|---|---|
basic | GitHub | Play Online |
CRUD | GitHub | Play Online |
You're welcome to submit an issue or PR!
See CHANGELOG.md for a history of changes to this plugin.
FAQs
Provide a file-based mock API for Vite in dev mode
We found that vite-plugin-simple-json-server demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.