A simple HTTP server that can be used to mock HTTP responses for testing purposes. Inspired by httpbin and built using nodejs and fastify with the idea of running it via https://mockhttp.org, via docker jaredwray/mockhttp, or nodejs npm install jaredwray/mockhttp.
Repo jaredwray/mockhttp, read from GitHub 16 h ago. jaredwray has not joined Take My Repo.
jaredwray/mockhttp is a public repo on GitHub by jaredwray. A simple HTTP server that can be used to mock HTTP responses for testing purposes. Inspired by httpbin and built using nodejs and fastify with the idea of running it via https://mockhttp.org, via docker jaredwray/mockhttp, or nodejs npm install jaredwray/mockhttp. It declares the MIT license on GitHub. It is written mainly in TypeScript, has 24 stars and last changed on 2026-11-20. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-23.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
A simple HTTP server that can be used to mock HTTP responses for testing purposes. Inspired by httpbin and built using nodejs and fastify with the idea of running it via https://mockhttp.org, via docker jaredwray/mockhttp, or nodejs npm install @jaredwray/mockhttp.
@fastify/helmet built in by defaultnodejs, typescript, and fastifydocker, nodejs, or Wasmer Edgedocker run -d -p 3000:3000 jaredwray/mockhttp
services:
mockhttp:
image: jaredwray/mockhttp:latest
ports:
- "3000:3000"
If you want to run it on a different port, just change the 3000 to whatever port you want and add in the environment variable PORT to the environment.
services:
mockhttp:
image: jaredwray/mockhttp:latest
ports:
- "3001:3001"
environment:
- PORT=3001
You can see an example of this in the docker-compose.yaml file.
npm install @jaredwray/mockhttp --save
then run mockhttp in your code.
import { MockHttp } from '@jaredwray/mockhttp';
const mock = new MockHttp();
await mock.start(); // start the server
const response = await fetch('http://localhost:3000/get');
console.log(response);
await mock.close(); // stop the server
Wasmer Edge runs the same Node server as Docker. deploy-wasmer.yaml publishes the source with wasmer deploy --build-remote, and the Anybuild file builds the server and the docs site. It runs when you start it by hand and when a GitHub Release is published. It does not deploy the Cloudflare Worker. The test app is mockhttp.wasmer.app.
Bins, taps, and @fastify/rate-limit are per instance on Wasmer. All mockhttp.org traffic stays on Cloudflare, where the rate limiter is shared across requests.
MockHttp supports HTTPS with auto-generated self-signed certificates or your own custom certificates. No external dependencies are required — certificate generation uses only Node.js built-in crypto.
The simplest way to enable HTTPS is to pass https: true. A self-signed certificate for localhost is generated automatically:
import { MockHttp } from '@jaredwray/mockhttp';
const mock = new MockHttp({ https: true });
await mock.start();
console.log(mock.isHttps); // true
// Use Fastify's built-in inject() for testing (no TLS setup needed)
const response = await mock.server.inject({ method: 'GET', url: '/get' });
console.log(response.statusCode); // 200
await mock.close();
Note: Self-signed certificates are not trusted by default. When making real HTTPS requests (e.g. with
fetch), setNODE_TLS_REJECT_UNAUTHORIZED=0in your test environment or use a custom HTTPS agent.
You can customize the auto-generated certificate by passing certificateOptions:
const mock = new MockHttp({
https: {
certificateOptions: {
commonName: 'my-test-server',
validityDays: 30,
keySize: 4096,
altNames: [
{ type: 'dns', value: 'example.local' },
{ type: 'dns', value: '*.example.local' },
{ type: 'ip', value: '192.168.1.100' },
],
},
},
});
await mock.start();
// Make requests...
await mock.close();
You can supply your own PEM-encoded certificate and key, either as strings or file paths:
// Using PEM strings
const mock = new MockHttp({
https: {
cert: '-----BEGIN CERTIFICATE-----\n...',
key: '-----BEGIN PRIVATE KEY-----\n...',
},
});
await mock.start();
// Make requests...
await mock.close();
// Using file paths
const mock = new MockHttp({
https: {
cert: '/path/to/cert.pem',
key: '/path/to/key.pem',
},
});
await mock.start();
// Make requests...
await mock.close();
You can also generate certificates independently using the exported utility functions:
import { generateCertificate, generateCertificateFiles } from '@jaredwray/mockhttp';
// Generate in-memory PEM strings
const { cert, key } = generateCertificate({
commonName: 'my-app',
validityDays: 90,
});
// Generate and write to disk
const result = await generateCertificateFiles({
certPath: './certs/cert.pem',
keyPath: './certs/key.pem',
commonName: 'my-app',
});
| Option | Type | Default | Description |
|---|---|---|---|
cert |
string | — | PEM-encoded certificate string or file path |
key |
string | — | PEM-encoded private key string or file path |
autoGenerate |
boolean | true |
Auto-generate a self-signed certificate when cert/key are not provided |
certificateOptions |
CertificateOptions | — | Options for the auto-generated certificate |
| Option | Type | Default | Description |
|---|---|---|---|
commonName |
string | 'localhost' |
Certificate subject Common Name (CN) |
altNames |
Array<{ type, value }> | [dns:localhost, ip:127.0.0.1, ip:::1] |
Subject Alternative Names with type 'dns' or 'ip' |
validityDays |
number | 365 |
Certificate validity period in days |
keySize |
number | 2048 |
RSA key size in bits |
MockHttp supports HTTP/2 in two modes:
http2: true and https: truehttp2: true, useful for service-to-service testingimport { MockHttp } from '@jaredwray/mockhttp';
const mock = new MockHttp({ http2: true, https: true });
await mock.start();
console.log(mock.http2); // true
console.log(mock.isHttps); // true
const response = await mock.server.inject({ method: 'GET', url: '/get' });
console.log(response.statusCode); // 200
await mock.close();
By default, HTTP/1.1 clients can still connect via ALPN negotiation (http1 defaults to true). To disable HTTP/1.1 fallback:
const mock = new MockHttp({ http2: true, https: true, http1: false });
await mock.start();
const mock = new MockHttp({ http2: true });
await mock.start();
console.log(mock.http2); // true
await mock.close();
Note: Browsers do not support h2c. This mode is useful for testing gRPC or service-to-service communication.
HTTP2=true node your-app.js
The injection/tap feature allows you to "tap into" the request flow and inject custom responses for specific requests. This is particularly useful for:
A "tap" is a reference to an injected response, similar to "wiretapping" - you're intercepting requests and returning predefined responses. Each tap can be removed when you're done with it, restoring normal server behavior.
import { mockhttp } from '@jaredwray/mockhttp';
const mock = new mockhttp();
await mock.start();
// Inject a simple response
const tap = mock.taps.inject(
{
response: "Hello, World!",
statusCode: 200,
headers: { "Content-Type": "text/plain" }
},
{
url: "/api/greeting",
method: "GET"
}
);
// Make requests - they will get the injected response
const response = await fetch('http://localhost:3000/api/greeting');
console.log(await response.text()); // "Hello, World!"
// Remove the injection when done
mock.taps.removeInjection(tap);
await mock.close();
const tap = mock.taps.inject(
{
response: { message: "Success", data: { id: 123 } },
statusCode: 200
},
{ url: "/api/users/123" }
);
// Match all requests under /api/
const tap = mock.taps.inject(
{
response: "API is mocked",
statusCode: 503
},
{ url: "/api/*" }
);
const tap1 = mock.taps.inject(
{ response: "Users data" },
{ url: "/api/users" }
);
const tap2 = mock.taps.inject(
{ response: "Posts data" },
{ url: "/api/posts" }
);
// View all active injections
console.log(mock.taps.injections); // Map of all active taps
// Remove specific injections
mock.taps.removeInjection(tap1);
mock.taps.removeInjection(tap2);
// Only intercept POST requests
const tap = mock.taps.inject(
{ response: "Created", statusCode: 201 },
{ url: "/api/users", method: "POST" }
);
const tap = mock.taps.inject(
{ response: "Authenticated response" },
{
url: "/api/secure",
headers: {
"authorization": "Bearer token123"
}
}
);
// Match ALL requests (no matcher specified)
const tap = mock.taps.inject({
response: "Server is in maintenance mode",
statusCode: 503
});
You can provide a function that dynamically generates the response based on the incoming request:
// Function response with access to the request object
const tap = mock.taps.inject(
(request) => {
return {
response: {
message: `You requested ${request.url}`,
method: request.method,
timestamp: new Date().toISOString()
},
statusCode: 200,
headers: {
"X-Request-Path": request.url
}
};
},
{ url: "/api/*" }
);
// Conditional responses based on request
const tap = mock.taps.inject((request) => {
// Return error for URLs containing 'error'
if (request.url.includes('error')) {
return {
response: { error: "Something went wrong" },
statusCode: 500
};
}
// Return success for everything else
return {
response: { status: "success" },
statusCode: 200
};
});
// Dynamic headers based on request
const tap = mock.taps.inject(
(request) => ({
response: "OK",
statusCode: 200,
headers: {
"X-Original-Method": request.method,
"X-Original-URL": request.url,
"X-Original-Host": request.hostname
}
}),
{ url: "/api/mirror" }
);
Bins are ephemeral URL endpoints that capture incoming HTTP requests so you can inspect them later. They're the inverse of Taps: instead of injecting a response, they record everything they receive. Useful for:
There are two URL prefixes:
/bins — JSON management API. Create, read, clear, and delete need the owner token./b/:id — the capture URL. Any HTTP method, any sub-path, any body sent
here is stored against bin :idPOST /bins returns an owner token one time. The server stores only the SHA-256 hash of that token.
Send this header on every management call:
Authorization: Bearer <token>
GET /bins returns only the bin for that token. It does not return other bins.
Send no token and the route returns HTTP 401. Send a token that does not match and the route returns HTTP 404. A missing bin returns the same HTTP 404. The response does not show that the bin exists.
The capture URL /b/:id stays open. A caller does not send the owner token to record a request.
The curl examples below use $TOKEN. $TOKEN is the owner token from POST /bins.
# 1. create a bin and keep the owner token
curl -s -X POST http://localhost:3000/bins
# → { "id": "abc123def456", "token": "<owner-token>",
# "url": "http://localhost:3000/b/abc123def456",
# "createdAt": "2026-05-18T12:00:00.000Z",
# "expiresAt": "2026-05-19T12:00:00.000Z",
# "requestCount": 0 }
# 2. send anything to the capture URL
curl -X POST "http://localhost:3000/b/abc123def456/webhook?source=stripe" \
-H 'content-type: application/json' \
-d '{"event":"payment.succeeded"}'
# → { "ok": true, "binId": "abc123def456", "requestId": "f9c2e1a40b3d" }
# 3. list captured requests (newest first)
curl -H "Authorization: Bearer <owner-token>" \
http://localhost:3000/bins/abc123def456/requests
| Method | Path | Description |
|---|---|---|
| POST | /bins |
Create a bin and return the owner token one time |
| GET | /bins |
List the bin for the Bearer token |
| GET | /bins/:id |
Read bin metadata. Needs the owner token |
| GET | /bins/:id/requests |
List captured requests. Needs the owner token |
| GET | /bins/:id/requests/:reqId |
Read one captured request. Needs the owner token |
| DELETE | /bins/:id/requests |
Clear captured requests. Needs the owner token |
| DELETE | /bins/:id |
Delete a bin. Needs the owner token |
| ANY | /b/:id and /b/:id/* |
Capture requests. No owner token |
Management routes need Authorization: Bearer <token>. The capture routes do not.
A complete walkthrough using curl:
BASE=http://localhost:3000
# Create the bin and grab its id
CREATE=$(curl -s -X POST $BASE/bins)
ID=$(echo "$CREATE" | jq -r .id)
TOKEN=$(echo "$CREATE" | jq -r .token)
echo "Bin URL: $BASE/b/$ID"
# Simulate a Stripe webhook
curl -s -X POST "$BASE/b/$ID/stripe/events?secret=whsec_test" \
-H 'content-type: application/json' \
-H 'stripe-signature: t=1700000000,v1=abc123' \
-d '{"id":"evt_1","type":"payment_intent.succeeded","data":{"object":{"amount":2000}}}'
# Simulate a GitHub webhook
curl -s -X POST "$BASE/b/$ID/github" \
-H 'content-type: application/json' \
-H 'x-github-event: pull_request' \
-d '{"action":"opened","number":42}'
# Inspect everything that arrived
curl -s -H "Authorization: Bearer $TOKEN" "$BASE/bins/$ID/requests" | jq
# Drill into the most recent one
RID=$(curl -s -H "Authorization: Bearer $TOKEN" "$BASE/bins/$ID/requests" | jq -r '.requests[0].id')
curl -s -H "Authorization: Bearer $TOKEN" "$BASE/bins/$ID/requests/$RID" | jq
# {
# "id": "f9c2e1a40b3d",
# "binId": "abc123def456",
# "method": "POST",
# "url": "/github",
# "path": "/github",
# "query": {},
# "headers": {
# "host": "localhost:3000",
# "content-type": "application/json",
# "x-github-event": "pull_request"
# },
# "remoteAddress": "127.0.0.1",
# "contentType": "application/json",
# "bodySize": 32,
# "body": "{\"action\":\"opened\",\"number\":42}",
# "bodyEncoding": "utf8",
# "truncated": false,
# "capturedAt": "2026-05-18T12:00:01.234Z"
# }
# Clean up
curl -s -X DELETE -H "Authorization: Bearer $TOKEN" "$BASE/bins/$ID/requests" # clear captures, keep the bin
curl -s -X DELETE -H "Authorization: Bearer $TOKEN" "$BASE/bins/$ID" # delete the bin entirely
{
"id": "f9c2e1a40b3d",
"binId": "abc123def456",
"method": "POST",
"url": "/webhook?source=stripe",
"path": "/webhook",
"query": { "source": "stripe" },
"headers": { "content-type": "application/json", "...": "..." },
"remoteAddress": "127.0.0.1",
"contentType": "application/json",
"bodySize": 32,
"body": "{\"event\":\"payment.succeeded\"}",
"bodyEncoding": "utf8",
"truncated": false,
"capturedAt": "2026-05-18T12:00:00.000Z"
}
url is the request URL relative to the bin (everything after /b/:id).path is the sub-path only, without the query string.bodyEncoding is "utf8" for text content types (text/*, application/json,
application/xml, application/x-www-form-urlencoded, application/javascript),
"base64" for everything else (binary payloads), or "none" when no body
was sent.truncated is true when the body exceeded maxBodySize and was cut
off. bodySize reflects the original length.JSON, XML, form-encoded, plain text, and JavaScript are stored as UTF-8 strings so you can read them directly:
curl -X POST "http://localhost:3000/b/$ID" \
-H 'content-type: application/json' \
-d '{"hello":"world"}'
curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3000/bins/$ID/requests" | jq '.requests[0] | {bodyEncoding, body}'
# {
# "bodyEncoding": "utf8",
# "body": "{\"hello\":\"world\"}"
# }
Any non-text content type is base64-encoded, preserving the bytes exactly:
# Upload a PNG to the bin
curl -X POST "http://localhost:3000/b/$ID/upload" \
-H 'content-type: image/png' \
--data-binary @logo.png
curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3000/bins/$ID/requests" | jq '.requests[0] | {bodyEncoding, bodySize}'
# {
# "bodyEncoding": "base64",
# "bodySize": 14823
# }
# Decode the body back to bytes
curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3000/bins/$ID/requests" \
| jq -r '.requests[0].body' | base64 -d > recovered.png
Bodies larger than maxBodySize (128 KiB by default) are cut off and flagged:
// In test setup
import { MockHttp, MockHttpBins } from '@jaredwray/mockhttp';
const mock = new MockHttp();
mock.bins = new MockHttpBins({ maxBodySize: 1024 }); // 1 KiB cap
await mock.start();
# Send 5000 bytes to a bin with a 1 KiB cap
head -c 5000 /dev/urandom | curl -X POST "http://localhost:3000/b/$ID" \
-H 'content-type: application/octet-stream' \
--data-binary @-
curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3000/bins/$ID/requests" | jq '.requests[0] | {bodySize, truncated, body_len: (.body | length)}'
# {
# "bodySize": 5000, ← original size
# "truncated": true,
# "body_len": 1368 ← base64 of the first 1024 bytes
# }
Once a bin reaches maxRequestsPerBin captures (100 by default), the oldest
ones are dropped:
# Send 105 requests
for i in $(seq 1 105); do
curl -s -X POST "http://localhost:3000/b/$ID/event/$i" > /dev/null
done
# The bin holds the most recent 100; the first 5 are gone
curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3000/bins/$ID/requests" | jq '.requests | length'
# 100
# Newest is at the top
curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3000/bins/$ID/requests" | jq '.requests[0].path'
# "/event/105"
Use mock.bins to control request bins from a test. You do not need an HTTP call:
import { MockHttp } from '@jaredwray/mockhttp';
const mock = new MockHttp({ logging: false });
await mock.start();
// Create a bin
const bin = await mock.bins.createBin();
console.log(`Webhook target: http://localhost:${mock.port}/b/${bin.id}`);
// ... point your code-under-test at that URL ...
// Read captured requests (newest first)
const requests = await mock.bins.getRequests(bin.id);
console.log(`Captured ${requests.length} requests`);
for (const req of requests) {
console.log(`${req.method} ${req.path} (${req.bodySize} bytes)`);
}
// Clean up
await mock.bins.deleteBin(bin.id);
await mock.close();
import { afterAll, beforeAll, expect, test } from 'vitest';
import { MockHttp } from '@jaredwray/mockhttp';
let mock: MockHttp;
beforeAll(async () => {
mock = new MockHttp({ logging: false });
await mock.start();
});
afterAll(async () => {
await mock.close();
});
test('my SDK sends the right webhook payload', async () => {
const bin = await mock.bins.createBin();
const webhookUrl = `http://localhost:${mock.port}/b/${bin.id}`;
// Drive your SDK at the bin
await mySdk.notify(webhookUrl, { event: 'user.created', id: 42 });
// Assert on what actually arrived
const [captured] = await mock.bins.getRequests(bin.id);
expect(captured.method).toBe('POST');
expect(captured.contentType).toBe('application/json');
expect(JSON.parse(captured.body!)).toEqual({
event: 'user.created',
id: 42,
});
expect(captured.headers['x-signature']).toBeDefined();
});
Bins are enabled by default. To disable the routes entirely:
const mock = new MockHttp({
httpBin: { bins: false },
});
To change the limits, replace the default MockHttpBins before you start the server:
import { MockHttp, MockHttpBins } from '@jaredwray/mockhttp';
const mock = new MockHttp();
mock.bins = new MockHttpBins({
defaultTtlMs: 60 * 60 * 1000, // 1 hour (default: 24h)
maxRequestsPerBin: 500, // (default: 100)
maxBodySize: 512 * 1024, // 512 KiB (default: 128 KiB)
idLength: 16, // (default: 12)
});
await mock.start();
| Option | Default | Description |
|---|---|---|
defaultTtlMs |
86400000 (24h) |
Bin lifetime, set as the Keyv TTL. An expired bin returns 404. |
maxRequestsPerBin |
100 |
When exceeded, oldest captures are dropped (FIFO). |
maxBodySize |
131072 (128 KiB) |
Larger bodies are truncated; truncated: true is set on the capture. |
idLength |
12 |
Length of generated bin and request ids. |
keyv |
new Keyv() |
Keyv store for bins. The default keeps bins in memory. |
MockHttpBins stores each bin in Keyv 6. The default is new Keyv(). That store keeps the data in memory for this process.
Pass a Keyv 6 instance when you want a different adapter. Install the adapter in your project. This package does not include an adapter. @keyv/redis 6 matches this Keyv version.
import Keyv from 'keyv';
import KeyvRedis from '@keyv/redis'; // pnpm add @keyv/redis
import { MockHttpBins } from '@jaredwray/mockhttp';
mock.bins = new MockHttpBins({
keyv: new Keyv({ store: new KeyvRedis('redis://localhost:6379') }),
});
Each capture writes the full bin again. A large body or a high request limit makes that write large. Set maxBodySize and maxRequestsPerBin to limit the size. With the defaults, a full bin of binary bodies is about 17 MB.
Two processes that share one Keyv can lose a capture. This occurs when both processes write the same bin at the same time. Keyv does not offer a conditional create, so two processes can also replace a new bin. Two instances in one process that share one Keyv wait on the same bin id.
If Keyv does not store a write, the bin route returns 500 with the standard Fastify error body: statusCode, error, and message.
A failed read depends on the Keyv error listener. Without a listener, Keyv throws the store error and the route returns 500. With a listener, Keyv does not throw. A failed read then looks like a missing bin, and the route returns 404. listBins() returns only the bins that it read before the error.
listBins() throws an error when the adapter has no iterator.
An expired bin returns 404. The in-memory Keyv store deletes an expired bin only when a read or listBins() reaches it. Until then, the bin stays in memory.
MockHttp supports rate limiting using @fastify/rate-limit. Rate limiting is enabled by default at 1000 requests per minute with localhost (127.0.0.1 and ::1) excluded from rate limiting.
By default, MockHttp applies the following rate limit:
import { MockHttp } from '@jaredwray/mockhttp';
const mock = new MockHttp();
await mock.start();
// Rate limiting is active (1000 req/min) except for localhost
To customize rate limiting, pass a rateLimit configuration object when creating your MockHttp instance:
import { MockHttp } from '@jaredwray/mockhttp';
const mock = new MockHttp({
rateLimit: {
max: 100, // Maximum 100 requests
timeWindow: '1 minute' // Per 1 minute window
}
});
await mock.start();
The rateLimit option accepts all @fastify/rate-limit options:
// Limit to 50 requests per minute
const mock = new MockHttp({
rateLimit: {
max: 50,
timeWindow: '1 minute'
}
});
const mock = new MockHttp({
rateLimit: {
max: 30,
timeWindow: 60000, // 1 minute in milliseconds
errorResponseBuilder: (req, context) => ({
statusCode: 429,
error: 'Too Many Requests',
message: `Rate limit exceeded. Try again in ${context.after}`
})
}
});
const mock = new MockHttp({
rateLimit: {
max: 100,
timeWindow: '1 minute',
allowList: ['127.0.0.1', '192.168.1.100'] // These IPs bypass rate limiting
}
});
const mock = new MockHttp({
rateLimit: {
max: 100,
timeWindow: '1 minute',
keyGenerator: (request) => {
// Rate limit by API key instead of IP
return request.headers['x-api-key'] || request.ip;
}
}
});
const mock = new MockHttp({
rateLimit: {
global: true, // Apply to all routes
max: 100, // Max requests
timeWindow: '1 minute', // Time window
cache: 10000, // Cache size for tracking clients
skipOnError: false, // Don't skip on storage errors
ban: 10, // Ban after 10 rate limit violations
continueExceeding: false, // Don't reset window on each request
enableDraftSpec: true, // Use IETF draft spec headers
addHeaders: { // Customize rate limit headers
'x-ratelimit-limit': true,
'x-ratelimit-remaining': true,
'x-ratelimit-reset': true
}
}
});
To disable rate limiting completely, set the rateLimit option to false:
const mock = new MockHttp({
rateLimit: false // Completely disable rate limiting
});
await mock.start();
// No rate limiting is applied to any requests
Note: To change rate limiting settings after the server has started, you must restart the server:
const mock = new MockHttp();
await mock.start(); // Starts with default rate limiting
// To change or disable rate limiting:
await mock.close();
mock.rateLimit = undefined; // or set new options
await mock.start(); // Restarts with new settings
| Option | Type | Default | Description |
|---|---|---|---|
max |
number | function | 1000 |
Maximum requests per time window |
timeWindow |
number | string | 60000 |
Duration of rate limit window (milliseconds or string like '1 minute') |
cache |
number | 5000 |
LRU cache size for tracking clients |
allowList |
array | function | [] |
IPs or function to exclude from rate limiting |
keyGenerator |
function | IP-based | Function to generate unique client identifier |
errorResponseBuilder |
function | Default 429 | Custom error response function |
skipOnError |
boolean | false |
Skip rate limiting if storage errors occur |
ban |
number | -1 |
Ban client after N violations (disabled by default) |
continueExceeding |
boolean | false |
Renew time window on each request while limited |
enableDraftSpec |
boolean | false |
Use IETF draft specification headers |
For the complete list of options, see the @fastify/rate-limit documentation.
MockHttp uses Pino for logging via Fastify's built-in logger. Logging is enabled by default but can be disabled when needed.
import { MockHttp } from '@jaredwray/mockhttp';
const mock = new MockHttp({ logging: false });
await mock.start();
// Server runs silently without any log output
You can also disable logging via the LOGGING environment variable:
LOGGING=false node your-app.js
MockHttp ignores trailing path segments that come after the parsable portion of a URL. This is useful when a client appends extra data to a known endpoint — instead of returning 404, MockHttp serves the closest matching route.
For example, all of these are served by /status/:code:
GET /status/429
GET /status/429/
GET /status/429/foo
GET /status/429/foo/bar
The rewrite preserves the query string and only triggers when a more specific route exists; URLs whose first path segment doesn't correspond to a registered route still return 404.
new MockHttp(options?)
Parameters:
options? (MockHttpOptions):port?: number - The port to listen on (default: 3000)host?: string - The host to listen on (default: '0.0.0.0')autoDetectPort?: boolean - Auto-detect next available port if in use (default: true)helmet?: boolean - Use Helmet for security headers (default: true)apiDocs?: boolean - Serve the Docula documentation site and OpenAPI spec (default: true)siteDistPath?: string - Path to the built Docula site (default: the package site/dist directory)rateLimit?: RateLimitPluginOptions - Configure rate limiting (default: 1000 req/min, localhost excluded)logging?: boolean - Enable logging (default: true)staticFiles?: boolean - Serve files from the package public/ directory (default: true)pluginTimeout?: number - Fastify plugin boot timeout in milliseconds; 0 disables it (default: Fastify's timeout)httpBin?: HttpBinOptions - Configure which httpbin routes to enablehttpMethods?: boolean - Enable HTTP method routes (default: true)redirects?: boolean - Enable redirect routes (default: true)requestInspection?: boolean - Enable request inspection routes (default: true)responseInspection?: boolean - Enable response inspection routes (default: true)statusCodes?: boolean - Enable status code routes (default: true)responseFormats?: boolean - Enable response format routes (default: true)cookies?: boolean - Enable cookie routes (default: true)anything?: boolean - Enable anything routes (default: true)auth?: boolean - Enable authentication routes (default: true)images?: boolean - Enable image routes (default: true)bins?: boolean - Enable request bin routes /bins and /b/:id (default: true)https?: boolean | HttpsOptions - Enable HTTPS with auto-generated or custom certificates (default: undefined/disabled)http2?: boolean - Enable HTTP/2 support (default: false)http1?: boolean - Allow HTTP/1.1 fallback when using HTTP/2 with HTTPS (default: true)hookOptions?: HookifiedOptions - Hookified optionsport: number - Get/set the server porthost: string - Get/set the server hostautoDetectPort: boolean - Get/set auto-detect port behaviorhelmet: boolean - Get/set Helmet security headersapiDocs: boolean - Get/set whether the documentation site and OpenAPI spec are servedsiteDistPath: string - Get/set the path to the built Docula sitelogging: boolean - Get/set logging enabled statestaticFiles: boolean - Get/set whether files from public/ are servedpluginTimeout: number | undefined - Get/set Fastify plugin boot timeoutrateLimit: RateLimitPluginOptions | undefined - Get/set rate limiting optionshttpBin: HttpBinOptions - Get/set httpbin route optionshttps: HttpsOptions | undefined - Get/set HTTPS configurationisHttps: boolean - Whether the server is running with HTTPShttp2: boolean - Get/set HTTP/2 supporthttp1: boolean - Get/set HTTP/1.1 fallback for HTTP/2 with HTTPSserver: FastifyInstance - Get/set the Fastify server instancetaps: TapManager - Get/set the TapManager instancebins: MockHttpBins - Get or set the request binsasync initialize()Register plugins and routes without listening. Use server.inject() afterwards, or call start() to bind a port.
async start()Start the Fastify server. If already running, it will be closed and restarted.
async close()Stop the Fastify server.
async detectPort()Detect the next available port.
Returns: number - The available port
async registerApiDocs(fastifyInstance?)Register OpenAPI generation and the Docula documentation site.
async registerSwagger(fastifyInstance?)Register @fastify/swagger and the live /openapi.json spec route.
async registerSite(fastifyInstance?)Serve the built Docula site from siteDistPath when the directory exists.
async registerHttpMethods(fastifyInstance?)Register HTTP method routes (GET, POST, PUT, PATCH, DELETE).
async registerStatusCodeRoutes(fastifyInstance?)Register status code routes.
async registerRequestInspectionRoutes(fastifyInstance?)Register request inspection routes (headers, ip, user-agent).
async registerResponseInspectionRoutes(fastifyInstance?)Register response inspection routes (cache, etag, response-headers).
async registerResponseFormatRoutes(fastifyInstance?)Register response format routes (json, xml, html, etc.).
async registerRedirectRoutes(fastifyInstance?)Register redirect routes (absolute, relative, redirect-to).
async registerCookieRoutes(fastifyInstance?)Register cookie routes (get, set, delete).
async registerAnythingRoutes(fastifyInstance?)Register "anything" catch-all routes.
async registerAuthRoutes(fastifyInstance?)Register authentication routes (basic, bearer, digest, hidden-basic).
async registerImageRoutes(fastifyInstance?)Register image routes (jpeg, png, svg, webp) with content negotiation support.
async registerBinRoutes(fastifyInstance?)Register the request bin routes — management at /bins and capture at /b/:id.
Use mockHttp.bins to control request bins. See Request Bins for usage examples.
bins.createBin()Create a new bin with the configured TTL. Throws when Keyv does not store the bin.
Returns: Promise<Bin & { token: string }> — { id, createdAt, expiresAt, requestCount, token }
The token value is the owner secret. POST /bins returns it one time. Send it as Authorization: Bearer <token> on management routes. These in-process methods do not require the token.
bins.getBin(id)Look up a bin by id. Returns undefined if the bin does not exist or Keyv has expired it. When the Keyv instance has an error listener, a failed read also returns undefined.
Returns: Promise<Bin | undefined>
bins.listBins()List the bins that Keyv still holds. GET /bins returns only the bin for the presented Bearer token.
Returns: Promise<Bin[]>
bins.deleteBin(id)Delete a bin and all its captured requests. The delete waits for captures already queued for that bin.
Returns: Promise<boolean> — true when the bin existed
bins.getRequests(binId)List captured requests for a bin, newest first.
Returns: Promise<CapturedRequest[]>
bins.getRequest(binId, reqId)Look up a single captured request.
Returns: Promise<CapturedRequest | undefined>
bins.clearRequests(binId)Clear all captured requests in a bin. The bin stays. Throws when Keyv does not store the change.
Returns: Promise<boolean> — false when the bin does not exist
bins.recordRequest(binId, raw)Manually record a captured request. Returns undefined if the bin does not exist. Throws when Keyv does not store the capture. Normally invoked by the capture route, but available for programmatic use.
Returns: Promise<CapturedRequest | undefined>
bins.maxBodySize / bins.maxRequestsPerBin / bins.defaultTtlMsRead-only getters for the currently-configured limits.
Access the TapManager via mockHttp.taps to inject custom responses.
taps.inject(response, matcher?)Injects a custom response for requests matching the criteria.
Parameters:
response (InjectionResponse | InjectionResponseFunction):
response: string | object | Buffer - The response bodystatusCode?: number - HTTP status code (default: 200)headers?: object - Response headers(request: FastifyRequest) => InjectionResponsematcher? (InjectionMatcher) - Optional matching criteria:
url?: string - URL path (supports wildcards with *)method?: string - HTTP method (GET, POST, etc.)hostname?: string - Hostname to matchheaders?: object - Headers that must be presentReturns: InjectionTap - A tap object with a unique id that can be used to remove the injection
taps.removeInjection(tapOrId)Removes an injection.
Parameters:
tapOrId: InjectionTap | string - The tap object or tap ID to removeReturns: boolean - true if removed, false if not found
taps.injectionsA getter that returns a Map of all active injection taps.
Returns: Map<string, InjectionTap> - Map of all active injections with tap IDs as keys
taps.clear()Removes all injections.
taps.hasInjectionsA getter that returns whether there are any active injections.
Returns: boolean - true if there are active injections, false otherwise
mockhttp.org is a free hosted instance of this codebase for testing. It runs on a Cloudflare Worker (no containers): documentation is served from Workers Assets, and mock APIs such as /get and /post run in the Worker. The service is globally available and rate-limited (1000 requests per minute per IP) to prevent abuse. Request bins on this service are stored in MongoDB Atlas, in the bins collection, so they are shared across isolates.
All mockhttp.org traffic stays on Cloudflare. A separate test app runs the Node server on Wasmer Edge at mockhttp.wasmer.app.
Getting Started is served at / and /docs, other guides at /docs/..., and the interactive HTTP API reference at /api. Mock endpoints such as /get and /post are unchanged.
Please read our CODE OF CONDUCT and CONTRIBUTING for details on our code of conduct, and the process for submitting pull requests to us.
jaredwray/mockhttp is a public repo on GitHub by jaredwray. A simple HTTP server that can be used to mock HTTP responses for testing purposes. Inspired by httpbin and built using nodejs and fastify with the idea of running it via https://mockhttp.org, via docker jaredwray/mockhttp, or nodejs npm install jaredwray/mockhttp.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-11-20. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
HTTP Request & Response Service, written in Python + Flask.
Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

A list of Free Software network services and web applications which can be hosted on your own servers
:zap: The one-liner node.js http-proxy-middleware (httpxy) for connect, express, next.js and more
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/jaredwray/mockhttpTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.