{"id":13400,"library":"json-server-auth","title":"JSON Server Auth","description":"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.","status":"active","version":"2.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/jeremyben/json-server-auth","tags":["javascript","JSON","server","fake","REST","API","prototyping","mock","mocking","typescript"],"install":[{"cmd":"npm install json-server-auth","lang":"bash","label":"npm"},{"cmd":"yarn add json-server-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add json-server-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"json-server-auth is a middleware designed to extend json-server's functionality, requiring it as a peer dependency.","package":"json-server","optional":false}],"imports":[{"note":"While CommonJS `require` still functions in many Node.js environments, ESM `import` is the preferred and modern approach for programmatic integration with JSON Server.","wrong":"const auth = require('json-server-auth');","symbol":"auth","correct":"import auth from 'json-server-auth';"},{"note":"Import types for configuration options, such as `AuthOptions`, when setting up programmatically in TypeScript environments.","symbol":"AuthOptions","correct":"import type { AuthOptions } from 'json-server-auth';"},{"note":"Import types for API responses, like `AccessResponse` which contains the JWT accessToken, useful for client-side type checking.","symbol":"AccessResponse","correct":"import type { AccessResponse } from 'json-server-auth';"}],"quickstart":{"code":"npm install -D json-server json-server-auth\n\n// Create db.json in your project root:\n// {\n//   \"users\": [],\n//   \"posts\": []\n// }\n\n// Start the server (using json-server-auth's bundled CLI):\n// json-server-auth db.json\n\n// Example usage with Node.js fetch (run in a separate script or browser console):\nasync function runAuthFlow() {\n  const baseUrl = 'http://localhost:3000';\n\n  // Register a new user\n  console.log('Registering user...');\n  const registerRes = await fetch(`${baseUrl}/register`, {\n    method: 'POST',\n    headers: { 'Content-Type': 'application/json' },\n    body: JSON.stringify({ email: 'test@example.com', password: 'password123', name: 'Test User' })\n  });\n  const registerData = await registerRes.json();\n  console.log('Registered:', registerData);\n  let accessToken = registerData.accessToken;\n\n  // Login with existing user (if accessToken is not available, e.g., after server restart)\n  if (!accessToken) {\n    console.log('Logging in user...');\n    const loginRes = await fetch(`${baseUrl}/login`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({ email: 'test@example.com', password: 'password123' })\n    });\n    const loginData = await loginRes.json();\n    console.log('Logged in:', loginData);\n    accessToken = loginData.accessToken;\n  }\n\n  // Access a protected resource (e.g., 'posts' with default auth rules 640)\n  // 6: owner read/write, 4: logged-in read, 0: public no access\n  if (accessToken) {\n    console.log('Accessing protected posts...');\n    const postsRes = await fetch(`${baseUrl}/posts`, {\n      headers: { 'Authorization': `Bearer ${accessToken}` }\n    });\n    const postsData = await postsRes.json();\n    console.log('Posts:', postsData);\n  }\n}\n\n// Uncomment the line below and run this script to test the flow:\n// runAuthFlow().catch(console.error);\n","lang":"typescript","description":"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."},"warnings":[{"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.","message":"Major 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.","severity":"breaking","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"To 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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`.","message":"Confusion 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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`.","cause":"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.","error":"Error: Cannot find module 'json-server-auth'"},{"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`).","cause":"Attempting to access a protected resource without a valid JWT access token, or with insufficient permissions according to the configured authorization rules.","error":"HTTP 401 Unauthorized / HTTP 403 Forbidden"},{"fix":"Ensure your POST request body for `/register` or `/login` contains valid `email` and `password` properties, formatted as `application/json`.","cause":"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.","error":"HTTP 400 Bad Request - 'email' and 'password' are required"},{"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.","cause":"Attempting to register a new user with an email address that is already present in the `users` collection within your `db.json`.","error":"Error: email already exists"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"json-server-auth","cli_version":null}