Registry / web-framework / json-server-auth

json-server-auth

JSON →
library2.1.0jsnpmunverified

JSON Server Auth is a middleware that adds JWT-based authentication and authorization capabilities to JSON Server, enabling developers to quickly create mock REST APIs with realistic security flows for prototyping and testing. Currently at version 2.1.0, this package doesn't specify a fixed release cadence but generally follows the evolution of JSON Server. Its key differentiators include a simplified authentication flow with user registration and login endpoints (`/register`, `/login`), automatic password hashing with `bcryptjs`, and a Unix-like numeric permission system (e.g., `640`) for granular resource authorization based on owner, logged-in users, and public access. It integrates directly with JSON Server, either via its dedicated CLI or as a programmatic middleware, making it an efficient tool for front-end development requiring mock authentication without backend implementation.

npm install json-server-auth
INSTALL
IMPORT
SIG · JSON-SERVER-AUTH
J
json-server-auth
web-frameworkjavascriptv2.1.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

auth
import auth from 'json-server-auth';
const auth = require('json-server-auth');
While CommonJS `require` still functions in many Node.js environments, ESM `import` is the preferred and modern approach for programmatic integration with JSON Server.
AuthOptions
import type { AuthOptions } from 'json-server-auth';
Import types for configuration options, such as `AuthOptions`, when setting up programmatically in TypeScript environments.
AccessResponse
import type { AccessResponse } from 'json-server-auth';
Import types for API responses, like `AccessResponse` which contains the JWT accessToken, useful for client-side type checking.

This quickstart demonstrates how to install `json-server` and `json-server-auth`, create a basic `db.json` with a 'users' collection, start the server using the `json-server-auth` CLI, and then perform user registration, login, and access a protected resource using the obtained JWT access token. The TypeScript language is chosen as the library ships types.

npm install -D json-server json-server-auth // Create db.json in your project root: // { // "users": [], // "posts": [] // } // Start the server (using json-server-auth's bundled CLI): // json-server-auth db.json // Example usage with Node.js fetch (run in a separate script or browser console): async function runAuthFlow() { const baseUrl = 'http://localhost:3000'; // Register a new user console.log('Registering user...'); const registerRes = await fetch(`${baseUrl}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'test@example.com', password: 'password123', name: 'Test User' }) }); const registerData = await registerRes.json(); console.log('Registered:', registerData); let accessToken = registerData.accessToken; // Login with existing user (if accessToken is not available, e.g., after server restart) if (!accessToken) { console.log('Logging in user...'); const loginRes = await fetch(`${baseUrl}/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'test@example.com', password: 'password123' }) }); const loginData = await loginRes.json(); console.log('Logged in:', loginData); accessToken = loginData.accessToken; } // Access a protected resource (e.g., 'posts' with default auth rules 640) // 6: owner read/write, 4: logged-in read, 0: public no access if (accessToken) { console.log('Accessing protected posts...'); const postsRes = await fetch(`${baseUrl}/posts`, { headers: { 'Authorization': `Bearer ${accessToken}` } }); const postsData = await postsRes.json(); console.log('Posts:', postsData); } } // Uncomment the line below and run this script to test the flow: // runAuthFlow().catch(console.error);
json-server-auth --version
Debug
Known issues
breakingMajor version upgrades of `json-server-auth` or its peer dependency `json-server` (especially `json-server@1.x.x` and above) may introduce breaking changes to the underlying API or default behavior. Always review release notes for both packages before upgrading.
fix
Consult the specific release notes for `json-server-auth` and `json-server` when upgrading. Ensure your `db.json` structure and any programmatic configurations align with the new versions. Test existing authentication and authorization flows thoroughly.
affects: >=1.0.0
gotchaThe default JWT secret used by `json-server-auth` for signing tokens is suitable only for local development and prototyping. Using it in production-like environments poses a significant security risk.
fix
For any scenario beyond local development, configure a strong, unique JWT secret. This can typically be done via environment variables (e.g., `process.env.JWT_SECRET`) if using a custom `json-server` setup, or through specific configuration options if provided by the middleware.
affects: >=1.0.0
gotchaTo enable authentication features, your `db.json` file MUST include a `users` collection (e.g., `"users": []`). Without this, registration and login endpoints will not function correctly.
fix
Ensure your `db.json` file has an empty `users` array at minimum: `{"users": []}`. Additional user properties can be added upon successful registration or updates.
affects: >=1.0.0
gotchaConfusion often arises between running `json-server db.json -m ./node_modules/json-server-auth` and `json-server-auth db.json`. The latter is a convenience CLI that bundles json-server and its middleware, simplifying startup but potentially masking direct `json-server` options.
fix
Use `json-server-auth db.json` for straightforward setup. If you need fine-grained control over `json-server`'s internal configuration (e.g., custom routers, multiple middlewares), you might prefer a programmatic setup with `json-server` directly, explicitly importing and `app.use()`-ing `json-server-auth`.
affects: >=1.0.0
gotchaThe numeric authorization rules (e.g., `640`) for resource access can be initially confusing. Misunderstanding these permissions can lead to unintended public access or restricted access for authenticated users.
fix
Carefully review the documentation for the numeric permission system: the first digit for owner, second for logged-in users, third for public. '4' grants read, '2' grants write. Test your endpoints thoroughly with different user states (public, logged-in, resource owner) to ensure desired access control.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Cannot find module 'json-server-auth'
The `json-server-auth` package is not installed, or the path provided to `json-server -m` is incorrect, or your Node.js module resolution path is misconfigured.
fix
Run `npm install json-server json-server-auth` or `yarn add json-server json-server-auth` to ensure both packages are installed locally. If using `json-server -m`, verify the exact path to `node_modules/json-server-auth`.
HTTP 401 Unauthorized / HTTP 403 Forbidden
Attempting to access a protected resource without a valid JWT access token, or with insufficient permissions according to the configured authorization rules.
fix
Ensure your request includes an `Authorization: Bearer <accessToken>` header. Verify the access token is not expired and the user's role/ownership matches the resource's configured numeric authorization rules (e.g., `640`).
HTTP 400 Bad Request - 'email' and 'password' are required
Attempting to register or log in a user without providing both 'email' and 'password' in the request body, or with an incorrectly formatted JSON payload.
fix
Ensure your POST request body for `/register` or `/login` contains valid `email` and `password` properties, formatted as `application/json`.
Error: email already exists
Attempting to register a new user with an email address that is already present in the `users` collection within your `db.json`.
fix
Use a unique email address for new user registration, or if the user is already created, attempt to log in instead of registering again.
Upgrade
Version history
2.1.0latest on npm
Audit
Dependencies
json-serverrequiredjson-server-auth is a middleware designed to extend json-server's functionality, requiring it as a peer dependency.
Agent activity
14 hits · last 30 days
node
12
Amazon
1
OpenAI (training)
1
Resources