Dynamic responses with JavaScript

New in 1.2

A static body always returns the same thing. A dynamic body is JavaScript that builds the response from the real one: add a field, filter a list, return an error only for some requests.

Turn on “Allow User Scripts” once

Chrome only lets extensions run code you write after you allow it:

  1. Open chrome://extensions and click Details on Placebo API.
  2. Turn on Allow User Scripts. (In Chrome before 138, turn on Developer mode at the top right instead.)

The rule editor shows this with a button that opens the right page. Everything else in Placebo API works without it.

Write the function

In an Override response rule, set the body type to Dynamic (JavaScript). The editor starts you off with a template. Define modifyResponse(args) and return the body:

function modifyResponse(args) {
  const data = args.responseJSON;
  if (!data) return args.response;
  data.items = data.items.slice(0, 1); // keep only the first item
  return data; // an object is sent as JSON
}

It’s the same format Requestly uses, so their dynamic rules import as they are.

What args contains

Name What it is
method The request method, e.g. GET
url The full request URL
response The real response body as text, or null with Serve without network call
responseJSON The real body parsed as JSON, or null
responseType The real response’s content type
statusCode The real status, or null without a network call
requestHeaders Headers the page set, as an object
requestData The request body when it’s text, otherwise null

Return a string to send it as is, an object to send it as JSON, or nothing to keep the real body. The function may be async. The rule’s Status code field still sets the status.

Examples

Fake an error for one user only:

function modifyResponse(args) {
  if (args.url.includes("/users/42")) return { error: "account suspended" };
  return args.response;
}

Mock a list that grows with the request (with Serve without network call):

function modifyResponse(args) {
  const count = Number(new URL(args.url).searchParams.get("limit") || 3);
  return { items: Array.from({ length: count }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` })) };
}

Add a field the backend doesn’t send yet:

function modifyResponse(args) {
  const user = args.responseJSON;
  if (!user) return args.response;
  return { ...user, plan: "pro", betaFeatures: ["new-checkout"] };
}

Change one item in a list and leave the rest alone:

function modifyResponse(args) {
  const orders = args.responseJSON;
  if (!Array.isArray(orders)) return args.response;
  return orders.map((order) => (order.id === 1001 ? { ...order, status: "refunded" } : order));
}

Test an empty state:

function modifyResponse(args) {
  return { ...args.responseJSON, items: [], total: 0 };
}

Answer with what the page sent (with Serve without network call, method POST):

function modifyResponse(args) {
  const input = JSON.parse(args.requestData || "{}");
  return { id: Math.floor(Math.random() * 10000), ...input, createdAt: new Date().toISOString() };
}

Reject a form only for some input, e.g. to test validation messages:

function modifyResponse(args) {
  const input = JSON.parse(args.requestData || "{}");
  if (!String(input.email || "").endsWith("@example.com")) {
    return { errors: { email: "Use your work address" } };
  }
  return args.response;
}

Paginate a mocked list by the page parameter:

function modifyResponse(args) {
  const page = Number(new URL(args.url).searchParams.get("page") || 1);
  const perPage = 20, total = 95;
  const first = (page - 1) * perPage;
  const items = Array.from({ length: Math.max(0, Math.min(perPage, total - first)) }, (_, i) => ({ id: first + i + 1 }));
  return { items, page, total, hasMore: first + perPage < total };
}

Make an endpoint slow, to see your loading states (the function may be async):

async function modifyResponse(args) {
  await new Promise((resolve) => setTimeout(resolve, 3000)); // 3 seconds
  return args.response;
}

Fail every third request, to test retries. Variables on globalThis keep their value between requests in a tab until you reload it:

function modifyResponse(args) {
  globalThis.orderCalls = (globalThis.orderCalls || 0) + 1;
  if (globalThis.orderCalls % 3 === 0) return { error: "temporarily unavailable" };
  return args.response;
}

Answer by the request headers, e.g. a different user for another token:

function modifyResponse(args) {
  const auth = args.requestHeaders["Authorization"] || args.requestHeaders["authorization"] || "";
  if (auth.endsWith("admin-token")) return { ...args.responseJSON, role: "admin" };
  return args.response;
}

Change text that isn’t JSON, such as HTML or CSV fetched by the page:

function modifyResponse(args) {
  return (args.response || "").replaceAll("Free trial", "Trial ended");
}

The status code comes from the rule’s Status code field, not from the function. To return an error status only sometimes, combine two rules: a rule with status 500 for the URL that should fail, above the dynamic rule for the rest.

Errors and limits

  • If the function throws, the page gets the real response (or a 500 explaining the error, in mock mode) and the error is logged to the page console.
  • The function has 10 seconds to answer; after that it counts as failed, so keep delays shorter.
  • The code runs in the page’s tab, in a separate script world that pages can’t see into. It works even on sites with a strict Content Security Policy.
  • Code changes reach open tabs straight away in Chrome 135 and newer; in older versions, reload the page.

Team Rules with JavaScript

A teammate’s dynamic rule doesn’t run in your browser until you’ve looked at it: its switch is off and it’s marked review code. Switching it on shows you the code to approve. If anyone changes the code later, it switches off for you again until you review it. See Sync and Team Rules.

Something unclear or missing? Tell me, and I'll fix the docs.