Mock API NEW

Intercept fetch() requests and return fake responses -- no server required. Register mock routes with inline data or external JSON files, simulate network delays and error codes, persist mocks across page reloads, and share them between team members with export/import. Perfect for prototyping, testing, and offline development.

Quick Start

Three steps: register your mocks, enable interception, and use fetch() as usual.

js
import aura from 'aura.js';

// 1. Register mock routes
aura.mock.register('GET', '/api/users', {
  body: [
    { id: 1, name: 'Alex' },
    { id: 2, name: 'Jordan' },
  ],
});

// 2. Enable interception
aura.mock.enable();

// 3. Use fetch normally -- it returns mock data!
const res = await fetch('/api/users');
const users = await res.json();
console.log(users); // [{ id: 1, name: "Alex" }, ...]

register()

Register a single mock route. The pattern supports :param segments (e.g. /users/:id) and * wildcards. If a route with the same method and pattern already exists, it is replaced.

Inline data variant

register(method: string, pattern: string, def?: MockDefinition): void
ParamTypeDescription
methodstringHTTP method: 'GET', 'POST', 'PUT', 'DELETE', etc.
patternstringURL pattern. Supports :param and * wildcard.
defMockDefinition?Optional mock definition (see below).

MockDefinition

PropertyTypeDescription
statusnumber?HTTP status code. Default: 200.
bodyunknown?Response body. Will be JSON-serialized. Can also be a function (ctx) => value.
headersRecord<string, string>?Response headers. Content-Type: application/json is included by default.
delaynumber?Simulated network delay in ms. Default: 0.
js
// Simple GET with body
aura.mock.register('GET', '/api/users', {
  body: [{ id: 1, name: 'Alex' }],
});

// POST with custom status
aura.mock.register('POST', '/api/users', {
  status: 201,
  body: { id: 3, name: 'New User' },
});

// Dynamic route with :param
aura.mock.register('GET', '/api/users/:id', {
  body: { id: 1, name: 'Alex', email: 'alex@example.com' },
});

// Dynamic body using a function
aura.mock.register('GET', '/api/users/:id', {
  body: ({ params }) => ({
    id: Number(params.id),
    name: `User ${params.id}`,
  }),
});

// Wildcard: catch all under /api/legacy/*
aura.mock.register('GET', '/api/legacy/*', {
  status: 301,
  headers: { 'Location': '/api/v2' },
});

register() from file

Instead of passing inline data, pass a file path string as the third argument. The JSON file is fetched once (using the real fetch) and cached as the response body.

register(method: string, pattern: string, filePath: string): void
ParamTypeDescription
methodstringHTTP method.
patternstringURL pattern.
filePathstringPath to a local JSON file (relative to your app root).
js
// Load mock data from a JSON file
aura.mock.register('GET', '/api/products', '/mocks/products.json');
aura.mock.register('GET', '/api/categories', '/mocks/categories.json');

// The file is fetched with the real fetch (even if mocking is enabled)
// and its parsed JSON becomes the response body

load()

Bulk-register multiple mocks in a single call. Keys use the format "METHOD /path". Values can be MockDefinition objects or file path strings.

load(definitions: Record<string, MockDefinition | string>): void
ParamTypeDescription
definitionsRecord<string, MockDefinition | string>Map of "METHOD /path" to definition or file path.
js
aura.mock.load({
  'GET /api/users':      { body: [{ id: 1, name: 'Alex' }] },
  'POST /api/users':     { status: 201, body: { id: 2 } },
  'GET /api/users/:id':  { body: { id: 1, name: 'Alex' } },
  'DELETE /api/users/:id': { status: 204 },
  'GET /api/products':   '/mocks/products.json',
});

unregister()

Remove a specific mock by its method and pattern.

unregister(method: string, pattern: string): boolean
ParamTypeDescription
methodstringHTTP method.
patternstringThe exact pattern string used during registration.

Returns: true if the mock was found and removed, false otherwise.

js
aura.mock.unregister('GET', '/api/users');    // true
aura.mock.unregister('GET', '/api/nothing');   // false (not found)

clear()

Remove all registered mocks and clear the request log.

clear(): void
js
aura.mock.clear();
console.log(aura.mock.routes.length); // 0
console.log(aura.mock.log.length);    // 0

enable()

Activate mock interception by replacing window.fetch with the mock handler. The original fetch is preserved internally and restored when you call disable(). Calling enable() when already enabled is a no-op.

enable(): void
js
aura.mock.enable();
console.log(aura.mock.enabled); // true

// All fetch() calls now go through the mock layer
const res = await fetch('/api/users'); // returns mock data

disable()

Deactivate mock interception and restore the original window.fetch. Calling disable() when not enabled is a no-op.

disable(): void
js
aura.mock.disable();
console.log(aura.mock.enabled); // false

// fetch() now hits real endpoints again

passthrough()

Add URL prefixes that should always bypass mock interception and hit the real network, even when mocking is enabled. Useful for auth endpoints, CDN assets, or analytics.

passthrough(...prefixes: string[]): void
ParamTypeDescription
...prefixesstring[]One or more URL prefixes to pass through.
js
// These prefixes will always use the real fetch
aura.mock.passthrough(
  '/api/auth',
  'https://cdn.example.com',
  '/analytics'
);

aura.mock.enable();

// This hits a mock (if registered)
await fetch('/api/users');

// This always hits the real server
await fetch('/api/auth/login');

save()

Persist all current mock definitions to localStorage under the key __aura_mocks__. Use this to preserve your mock setup across page reloads.

save(): void
js
// Register mocks, then save
aura.mock.load({ 'GET /api/users': { body: [] } });
aura.mock.save();

// Mocks survive page refresh!

restore()

Load and register mocks previously saved to localStorage. By default, also calls enable() to activate interception immediately.

restore(autoEnable?: boolean): boolean
ParamTypeDescription
autoEnablebooleanAutomatically call enable() after restoring. Default: true.

Returns: true if mocks were found and restored, false if nothing was saved.

js
// On app startup, restore any saved mocks
if (aura.mock.restore()) {
  console.log('Mocks restored and enabled!');
}

// Restore without auto-enabling
aura.mock.restore(false);
// Mocks are loaded but fetch is not intercepted yet

clearSaved()

Remove persisted mocks from localStorage. Does not affect the currently registered in-memory mocks.

clearSaved(): void
js
aura.mock.clearSaved();
// localStorage key "__aura_mocks__" is removed

export()

Serialize all registered mocks to a JSON string. The output uses the same "METHOD /path" format as load(), making it easy to share mock configurations between developers.

export(): string

Returns: A pretty-printed JSON string.

js
const json = aura.mock.export();
console.log(json);
// {
//   "GET /api/users": {
//     "status": 200,
//     "body": [{ "id": 1, "name": "Alex" }],
//     "headers": { "Content-Type": "application/json" },
//     "delay": 0
//   }
// }

// Copy to clipboard for a teammate
navigator.clipboard.writeText(json);

import()

Import mocks from a JSON string (typically the output of export()). Internally calls load(), so existing mocks with the same method/pattern are replaced.

import(json: string): void
ParamTypeDescription
jsonstringA JSON string in the "METHOD /path" format.
js
// Paste a teammate's exported JSON
const shared = `{
  "GET /api/todos": { "body": [{ "id": 1, "text": "Ship it" }] },
  "POST /api/todos": { "status": 201, "body": { "id": 2 } }
}`;

aura.mock.import(shared);
aura.mock.enable();

log (property)

A read-only array of every request that has been intercepted since mocking was enabled. Each entry records the method, URL, whether it matched a registered mock, and the timestamp.

get log: ReadonlyArray<{ method: string; url: string; matched: boolean; timestamp: number }>
js
// After some fetch calls...
console.table(aura.mock.log);
// [
//   { method: "GET", url: "/api/users", matched: true, timestamp: 1710672000000 },
//   { method: "GET", url: "/api/unknown", matched: false, timestamp: 1710672001000 },
// ]

// Filter to see only unmatched requests (fell through to real fetch)
const missed = aura.mock.log.filter(e => !e.matched);
console.log('Unhandled requests:', missed);

routes (property)

A read-only array of all registered MockRoute definitions. Useful for debugging or displaying a list of available mocks.

get routes: MockRoute[]

Each MockRoute contains: method, pattern, status, body, headers, and delay.

js
console.table(aura.mock.routes);
// [
//   { method: "GET", pattern: "/api/users", status: 200, delay: 0, ... },
//   { method: "POST", pattern: "/api/users", status: 201, delay: 0, ... },
// ]

console.log(`${aura.mock.routes.length} mocks registered`);

enabled (property)

A boolean getter indicating whether mock interception is currently active.

get enabled: boolean
js
console.log(aura.mock.enabled); // false
aura.mock.enable();
console.log(aura.mock.enabled); // true

Recipes

Mock an entire backend

Use load() to define your complete API surface in one place. Combine inline data with JSON files for large datasets.

js — mocks/setup.js
import aura from 'aura.js';

aura.mock.load({
  // Auth
  'POST /api/auth/login': {
    body: { token: 'mock-jwt-token', user: { id: 1, name: 'Alex' } },
  },
  'POST /api/auth/logout': { status: 204 },

  // Users
  'GET /api/users':        '/mocks/users.json',
  'GET /api/users/:id':    { body: { id: 1, name: 'Alex' } },
  'POST /api/users':       { status: 201, body: { id: 99 } },
  'PUT /api/users/:id':    { body: { ok: true } },
  'DELETE /api/users/:id':  { status: 204 },

  // Products
  'GET /api/products':     '/mocks/products.json',
  'GET /api/products/:id': '/mocks/product-detail.json',
});

aura.mock.enable();
export default aura;

Simulate errors

Test how your app handles different HTTP error codes by setting the status field.

js
// 401 Unauthorized
aura.mock.register('GET', '/api/profile', {
  status: 401,
  body: { error: 'Token expired' },
});

// 500 Internal Server Error
aura.mock.register('POST', '/api/checkout', {
  status: 500,
  body: { error: 'Payment gateway timeout' },
});

// 422 Validation Error
aura.mock.register('POST', '/api/users', {
  status: 422,
  body: {
    errors: {
      email: ['Email is already taken'],
      name: ['Name is required'],
    },
  },
});

// 404 Not Found
aura.mock.register('GET', '/api/users/:id', {
  status: 404,
  body: { error: 'User not found' },
});

Add network delay

Use the delay field to simulate slow networks or loading states. This is invaluable for testing skeleton screens, spinners, and timeout handling.

js
// Simulate a slow API (2 seconds)
aura.mock.register('GET', '/api/dashboard', {
  delay: 2000,
  body: { stats: { users: 1420, revenue: 52300 } },
});

// Simulate a very slow file upload (5 seconds)
aura.mock.register('POST', '/api/upload', {
  delay: 5000,
  status: 201,
  body: { url: 'https://cdn.example.com/file.pdf' },
});

// Add a small realistic delay to all mocks
aura.mock.load({
  'GET /api/users':    { delay: 200, body: [] },
  'GET /api/posts':    { delay: 150, body: [] },
  'GET /api/comments': { delay: 300, body: [] },
});

Dev/prod toggle

Conditionally enable mocking based on environment, URL parameters, or localStorage flags.

js — main.js
import aura from 'aura.js';

// Option 1: Environment variable
if (import.meta.env.DEV) {
  await import('./mocks/setup.js');
}

// Option 2: URL param — add ?mock to any page
if (new URLSearchParams(location.search).has('mock')) {
  await import('./mocks/setup.js');
}

// Option 3: Restore from localStorage (saved from a previous session)
aura.mock.restore();

// Option 4: Combine — use saved mocks in dev, nothing in prod
if (import.meta.env.DEV) {
  if (!aura.mock.restore()) {
    // No saved mocks — load defaults
    await import('./mocks/setup.js');
  }
}

// Handy: expose to browser console for on-the-fly toggling
window.__mock = aura.mock;
// Then in DevTools: __mock.disable() / __mock.enable()

Share mocks between developers

Use export() and import() to share mock configurations via Slack, email, or version control.

js
// Developer A: export and copy to clipboard
const json = aura.mock.export();
navigator.clipboard.writeText(json);
console.log('Mocks copied! Send to your teammate.');

// Developer B: paste and import
const pasted = await navigator.clipboard.readText();
aura.mock.import(pasted);
aura.mock.enable();

// Or save the JSON as a file in your repo
// mocks/shared-mocks.json
// Then load at startup:
const res = await fetch('/mocks/shared-mocks.json');
const defs = await res.text();
aura.mock.import(defs);
aura.mock.enable();