Skip to content

Configuration Reference

Complete reference for mockd configuration files.

mockd supports YAML and JSON configuration files. The version field is required.

Terminal window
mockd serve --config mocks.yaml
mockd serve --config mocks.json
version: "1.0"
mocks:
- id: string
name: string
type: http | websocket | graphql | grpc | mqtt | soap
enabled: boolean
http: { ... } # if type: http
websocket: { ... } # if type: websocket
graphql: { ... } # if type: graphql
grpc: { ... } # if type: grpc
mqtt: { ... } # if type: mqtt
soap: { ... } # if type: soap
serverConfig: { ... } # Optional server settings
statefulResources: [ ... ] # Optional CRUD resources
FieldTypeRequiredDescription
versionstringYesConfig version (e.g., "1.0")
mocksarrayYesMock definitions
serverConfigobjectNoServer configuration
statefulResourcesarrayNoStateful CRUD resources

All mock types share common fields:

mocks:
- id: unique-mock-id
name: "Human-readable name"
description: "Optional description"
type: http
enabled: true
parentId: "" # Folder ID (optional)
metaSortKey: 0 # Sort order (optional)
http: { ... } # Type-specific configuration
FieldTypeRequiredDefaultDescription
idstringYesUnique identifier
typestringYesMock type: http, websocket, graphql, grpc, mqtt, soap
namestringNoHuman-readable name
descriptionstringNoLonger description
enabledbooleanNotrueWhether mock is active
parentIdstringNoFolder ID for organization
metaSortKeynumberNoManual ordering within folder

HTTP mocks match incoming requests and return configured responses.

mocks:
- id: get-users
name: Get Users
type: http
enabled: true
http:
priority: 0
matcher:
method: GET
path: /api/users
headers:
Authorization: "Bearer *"
queryParams:
status: active
response:
statusCode: 200
headers:
Content-Type: application/json
body: '{"users": []}'
delayMs: 100
FieldTypeDescription
priorityintegerMatch priority (higher = matches first)
matcherobjectRequest matching criteria
responseobjectResponse definition
sseobjectServer-Sent Events config (instead of response)
chunkedobjectChunked transfer config (instead of response)
validationobjectRequest validation (see Validation)
FieldTypeDescription
methodstringHTTP method (GET, POST, PUT, DELETE, PATCH, etc.)
pathstringExact URL path
pathPatternstringRegex pattern for URL path
headersmapHeader matchers (key: regex pattern)
queryParamsmapQuery parameter matchers (key: regex pattern)
bodyContainsstringBody must contain this string
bodyEqualsstringBody must equal this string exactly
bodyPatternstringBody must match this regex pattern
bodyJsonPathmapJSONPath matchers (path: expected value)
mtlsobjectmTLS client certificate matching
# Exact match
path: /api/users
# Path parameters
path: /api/users/{id}
path: /api/{resource}/{id}
# Greedy path parameter (matches multiple segments)
path: /api/files/{path:.*}
# Regex pattern
pathPattern: "/api/users/[0-9]+"
FieldTypeDefaultDescription
statusCodeinteger200HTTP status code
headersmap{}Response headers
bodystring""Response body (supports templates)
bodyFilestringLoad body from file path
delayMsinteger0Response delay in milliseconds
matcher:
mtls:
cn: "client.example.com" # Common Name pattern
ou: "Engineering" # Organizational Unit pattern
o: "Example Corp" # Organization pattern
san:
dns: "*.example.com" # DNS SAN pattern
email: "*@example.com" # Email SAN pattern
ip: "10.0.0.*" # IP SAN pattern
http:
matcher:
method: GET
path: /events
sse:
events:
- type: update
data: '{"status": "connected"}'
id: "1"
- type: update
data: '{"status": "processing"}'
delay: 1000
timing:
fixedDelay: 1000 # ms between events
initialDelay: 0 # ms before first event
lifecycle:
maxEvents: 10 # max events before closing
timeout: 60000 # connection timeout ms
keepaliveInterval: 15000 # keepalive interval ms
resume:
enabled: true # support Last-Event-ID
bufferSize: 100 # events to buffer
http:
matcher:
method: GET
path: /stream
chunked:
chunkSize: 1024 # bytes per chunk
chunkDelay: 100 # ms between chunks
data: "..." # data to stream
dataFile: ./large.json # or load from file
format: ndjson # optional: ndjson format
ndjsonItems: # for ndjson format
- {"id": 1}
- {"id": 2}

WebSocket mocks handle bidirectional message communication.

mocks:
- id: chat-ws
name: Chat WebSocket
type: websocket
enabled: true
websocket:
path: /ws/chat
subprotocols:
- chat
- json
requireSubprotocol: false
echoMode: true
maxMessageSize: 65536
idleTimeout: "5m"
maxConnections: 100
heartbeat:
enabled: true
interval: "30s"
timeout: "10s"
matchers:
- match:
type: exact
value: "ping"
response:
type: text
value: "pong"
- match:
type: json
path: "$.type"
value: "join"
response:
type: json
value:
type: "joined"
message: "Welcome!"
defaultResponse:
type: json
value:
type: "echo"
message: "{{message}}"
FieldTypeDefaultDescription
pathstringRequiredWebSocket upgrade path
subprotocolsarray[]Supported subprotocols
requireSubprotocolbooleanfalseRequire matching subprotocol
echoModebooleanfalseEcho received messages
maxMessageSizeinteger65536Max message size (bytes)
idleTimeoutstringConnection idle timeout
maxConnectionsinteger0Max concurrent connections (0 = unlimited)
heartbeatobjectPing/pong keepalive config
matchersarray[]Message matching rules
defaultResponseobjectResponse when no matcher matches
scenarioobjectScripted message sequence
FieldTypeDescription
typestringMatch type: exact, contains, regex, json
valuestringValue to match
pathstringJSONPath for json type
messageTypestringFilter by message type: text, binary
FieldTypeDescription
typestringResponse type: text, json, binary
valueanyResponse content (string or object for json)
delaystringDelay before sending (e.g., “100ms”)
FieldTypeDefaultDescription
enabledbooleanfalseEnable ping/pong
intervalstring"30s"Ping interval
timeoutstring"10s"Pong timeout
websocket:
scenario:
name: "onboarding"
loop: false
resetOnReconnect: true
steps:
- type: send
message:
type: json
value: {"type": "welcome"}
- type: wait
duration: "1s"
- type: waitFor
match:
type: json
path: "$.type"
value: "ready"
timeout: "10s"
optional: false

GraphQL mocks provide a full GraphQL API endpoint.

mocks:
- id: graphql-api
name: GraphQL API
type: graphql
enabled: true
graphql:
path: /graphql
introspection: true
schema: |
type Query {
users: [User!]!
user(id: ID!): User
}
type User {
id: ID!
name: String!
email: String!
}
resolvers:
Query.users:
response:
- id: "1"
name: "Alice"
email: "alice@example.com"
Query.user:
response:
id: "1"
name: "Alice"
email: "alice@example.com"
FieldTypeDefaultDescription
pathstringRequiredGraphQL endpoint path
schemastringInline SDL schema
schemaFilestringPath to .graphql schema file
introspectionbooleanfalseEnable introspection queries
resolversmap{}Field resolver configurations
subscriptionsmap{}Subscription configurations

Resolvers are keyed by Type.field:

resolvers:
Query.users:
response:
- { id: "1", name: "Alice" }
- { id: "2", name: "Bob" }
delay: "100ms"
Query.user:
# Match specific arguments
match:
args:
id: "1"
response:
id: "1"
name: "Alice"
Mutation.createUser:
response:
id: "{{uuid}}"
name: "New User"
Query.error:
error:
message: "Something went wrong"
path: ["error"]
extensions:
code: "INTERNAL_ERROR"

gRPC mocks provide a gRPC service endpoint.

mocks:
- id: grpc-greeter
name: Greeter Service
type: grpc
enabled: true
grpc:
port: 50051
reflection: true
protoFile: |
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
rpc SayHelloStream (HelloRequest) returns (stream HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
services:
helloworld.Greeter:
methods:
SayHello:
response:
message: "Hello, World!"
SayHelloStream:
responses:
- message: "Hello 1"
- message: "Hello 2"
- message: "Hello 3"
streamDelay: "500ms"
FieldTypeDefaultDescription
portintegerRequiredgRPC server port
protoFilestringInline proto definition
protoFilesarrayPaths to .proto files
importPathsarrayProto import paths
reflectionbooleanfalseEnable gRPC reflection
servicesmap{}Service configurations
services:
package.Service:
methods:
MethodName:
response: # Single response
field: value
responses: # Multiple responses (streaming)
- { field: value1 }
- { field: value2 }
delay: "100ms" # Response delay
streamDelay: "50ms" # Delay between stream messages
match: # Request matching
metadata:
authorization: "Bearer *"
request:
field: expected_value
error:
code: "NOT_FOUND"
message: "Resource not found"
details:
type: "ErrorInfo"

MQTT mocks provide an MQTT broker.

mocks:
- id: mqtt-broker
name: IoT MQTT Broker
type: mqtt
enabled: true
mqtt:
port: 1883
tls:
enabled: false
certFile: ./certs/mqtt.crt
keyFile: ./certs/mqtt.key
auth:
enabled: false
users:
- username: device
password: secret123
acl:
- topic: "sensors/#"
access: publish
- topic: "commands/#"
access: subscribe
topics:
- topic: sensors/temperature
qos: 1
retain: true
messages:
- payload: '{"temp": 22, "unit": "celsius"}'
interval: "5s"
repeat: true
- topic: commands/device/+
qos: 1
onPublish:
response:
payload: '{"status": "ack"}'
forward: responses/device
FieldTypeDefaultDescription
portintegerRequiredMQTT broker port
tlsobjectTLS configuration
authobjectAuthentication configuration
topicsarray[]Topic configurations
FieldTypeDefaultDescription
topicstringRequiredTopic pattern (supports + and # wildcards)
qosinteger0Quality of Service (0, 1, 2)
retainbooleanfalseRetain last message
messagesarrayMessages to publish
onPublishobjectHandler for received messages
deviceSimulationobjectSimulate multiple devices
FieldTypeDescription
payloadstringMessage payload (supports templates)
delaystringInitial delay before sending
intervalstringRepeat interval
repeatbooleanWhether to repeat

SOAP mocks provide SOAP/WSDL service endpoints.

mocks:
- id: soap-service
name: Calculator Service
type: soap
enabled: true
soap:
path: /soap/calculator
wsdlFile: ./calculator.wsdl # or inline with wsdl:
operations:
Add:
soapAction: "http://example.com/Add"
response: |
<AddResponse>
<AddResult>{{add request.a request.b}}</AddResult>
</AddResponse>
delay: "50ms"
match:
xpath:
"//a": "10"
fault:
code: "Server.InvalidInput"
message: "Invalid input provided"
detail: "<errorCode>1001</errorCode>"
FieldTypeDescription
pathstringSOAP endpoint path
wsdlstringInline WSDL definition
wsdlFilestringPath to WSDL file
operationsmapOperation configurations
FieldTypeDescription
soapActionstringSOAPAction header value
responsestringXML response body
delaystringResponse delay
matchobjectXPath-based request matching
faultobjectSOAP fault response

Server settings can be included in the config file.

Note: Port settings (httpPort, httpsPort, adminPort) from config files are currently overridden by CLI flags. Use --port and --admin-port flags to set ports:

Terminal window
mockd serve --config myconfig.yaml --port 8080 --admin-port 8081
version: "1.0"
serverConfig:
httpPort: 4280
httpsPort: 4283
adminPort: 4290
logRequests: true
maxLogEntries: 1000
maxBodySize: 10485760 # 10MB
readTimeout: 30 # seconds
writeTimeout: 30 # seconds
tls:
enabled: false
certFile: ./certs/server.crt
keyFile: ./certs/server.key
autoGenerateCert: true
mtls:
enabled: false
clientAuth: "require-and-verify"
caCertFile: ./certs/ca.crt
allowedCNs:
- "client.example.com"
mocks: [...]
FieldTypeDefaultDescription
httpPortinteger4280HTTP server port (0 = disabled)
httpsPortinteger0HTTPS server port (0 = disabled)
adminPortinteger4290Admin API port
managementPortinteger4281Engine management API port (internal)
logRequestsbooleantrueEnable request logging
maxLogEntriesinteger1000Max log entries to retain
maxBodySizeinteger10485760Max request body size (bytes)
readTimeoutinteger30HTTP read timeout (seconds)
writeTimeoutinteger30HTTP write timeout (seconds)

The managementPort is used for internal communication between the Admin API and the mock engine. In standalone mode, you typically don’t need to configure this.

FieldTypeDefaultDescription
enabledbooleanfalseEnable TLS/HTTPS
certFilestringPath to certificate file
keyFilestringPath to private key file
autoGenerateCertbooleanfalseAuto-generate self-signed cert
FieldTypeDefaultDescription
enabledbooleanfalseEnable mTLS
clientAuthstring"none"Client auth mode
caCertFilestringCA certificate file
caCertFilesarrayMultiple CA certificate files
allowedCNsarrayAllowed client Common Names
allowedOUsarrayAllowed Organizational Units

Client auth modes:

  • none - No client certificate requested
  • request - Client certificate requested but not required
  • require - Client certificate required but not verified
  • verify-if-given - Verify client certificate if provided
  • require-and-verify - Require and verify client certificate

Configure Cross-Origin Resource Sharing for the mock server.

serverConfig:
cors:
enabled: true
allowOrigins:
- "http://localhost:3000"
- "https://app.example.com"
allowMethods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
allowHeaders:
- Content-Type
- Authorization
- X-Requested-With
exposeHeaders:
- X-Request-ID
allowCredentials: false
maxAge: 86400
FieldTypeDefaultDescription
enabledbooleantrueEnable CORS handling
allowOriginsarray["http://localhost:*"]Allowed origins (use ["*"] for any)
allowMethodsarray[GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD]Allowed HTTP methods
allowHeadersarray[Content-Type, Authorization, X-Requested-With, Accept, Origin]Allowed request headers
exposeHeadersarray[]Headers browsers can access
allowCredentialsbooleanfalseAllow credentials (cannot use with * origin)
maxAgeinteger86400Preflight cache duration (seconds)

Default behavior: When not configured, mockd allows requests from localhost origins only. This is secure for local development while preventing cross-origin attacks.

Wildcard origins:

cors:
allowOrigins: ["*"] # Allow any origin (not recommended for production)

Note: When allowCredentials: true, you cannot use wildcard origins.

Configure rate limiting for the mock server.

serverConfig:
rateLimit:
enabled: true
requestsPerSecond: 1000
burstSize: 2000
trustedProxies:
- "10.0.0.0/8"
- "172.16.0.0/12"
FieldTypeDefaultDescription
enabledbooleanfalseEnable rate limiting
requestsPerSecondfloat1000Requests per second limit
burstSizeinteger2000Maximum burst size (token bucket)
trustedProxiesarray[]CIDR ranges for trusted proxies

How it works: Rate limiting uses a token bucket algorithm. The bucket fills at requestsPerSecond rate up to burstSize tokens. Each request consumes one token.

Trusted proxies: When set, mockd trusts X-Forwarded-For headers from these IP ranges for accurate client IP detection.

Example: Strict rate limiting for load testing:

serverConfig:
rateLimit:
enabled: true
requestsPerSecond: 100
burstSize: 150

Stateful resources provide automatic CRUD operations with persistent state.

version: "1.0"
statefulResources:
- name: users
basePath: /api/users
idField: id
parentField: ""
seedData:
- id: "1"
name: "Alice"
email: "alice@example.com"
- id: "2"
name: "Bob"
email: "bob@example.com"
mocks: []
FieldTypeDefaultDescription
namestringRequiredResource name (e.g., “users”)
basePathstringRequiredBase URL path (e.g., “/api/users”)
idFieldstring"id"Field name for resource ID
parentFieldstringParent FK field for nested resources
seedDataarray[]Initial data to load
validationobjectValidation rules (see Validation)

For a resource with basePath: /api/users:

MethodPathDescription
GET/api/usersList all resources
POST/api/usersCreate resource
GET/api/users/{id}Get resource by ID
PUT/api/users/{id}Replace resource
PATCH/api/users/{id}Update resource
DELETE/api/users/{id}Delete resource

Stateful resources and HTTP mocks support field-level request validation.

FieldTypeDefaultDescription
modestring"strict"Validation mode: strict, warn, permissive
autobooleanfalseAuto-infer rules from seed data
requiredarray[]Required field names (shared)
fieldsmap{}Field validators (shared)
pathParamsmap{}Path parameter validators
onCreateobjectCreate-specific validation
onUpdateobjectUpdate-specific validation
schemaobjectInline JSON Schema
schemaRefstringPath to JSON Schema file
FieldTypeDefaultDescription
modestring"strict"Validation mode: strict, warn, permissive
failStatusinteger400HTTP status code for failures
requiredarray[]Required field names
fieldsmap{}Field validators
pathParamsmap{}Path parameter validators
queryParamsmap{}Query parameter validators
headersmap{}Header validators
schemaobjectInline JSON Schema
schemaRefstringPath to JSON Schema file
FieldTypeDescription
typestringExpected type: string, number, integer, boolean, array, object
requiredbooleanField must be present
nullablebooleanAllow null values
minLengthintegerMinimum string length
maxLengthintegerMaximum string length
patternstringRegex pattern for strings
formatstringFormat: email, uuid, date, datetime, uri, ipv4, ipv6, hostname
minnumberMinimum value (inclusive)
maxnumberMaximum value (inclusive)
exclusiveMinnumberMinimum value (exclusive)
exclusiveMaxnumberMaximum value (exclusive)
minItemsintegerMinimum array items
maxItemsintegerMaximum array items
uniqueItemsbooleanArray items must be unique
itemsobjectFieldValidator for array items
enumarrayAllowed values
propertiesmapNested object validators
messagestringCustom error message

Use dot notation for nested object fields:

fields:
"address.city":
type: string
required: true
"address.zipCode":
type: string
pattern: "^[0-9]{5}$"
"items.sku":
type: string
required: true

For arrays, the field after the dot applies to each array item:

  • items.sku validates the sku field in each item of the items array

See the Validation Guide for comprehensive examples.


Response bodies support template variables:

body: |
{
"id": "{{request.pathParam.id}}",
"query": "{{request.query.search}}",
"header": "{{request.header.Authorization}}",
"body": {{request.body}},
"field": "{{jsonPath request.body '$.field'}}",
"timestamp": "{{now}}",
"unix": "{{timestamp}}",
"uuid": "{{uuid}}",
"random": {{randomInt 1 100}}
}
VariableDescription
{{request.method}}HTTP method
{{request.path}}Request path
{{request.url}}Full URL
{{request.pathParam.name}}Path parameter value
{{request.query.name}}Query parameter value
{{request.header.Name}}Request header value
{{request.body}}Full request body (raw)
{{jsonPath request.body '$.path'}}JSONPath extraction
{{now}}ISO 8601 timestamp
{{timestamp}}Unix timestamp (seconds)
{{uuid}}Random UUID
{{randomInt min max}}Random integer
{{randomFloat min max}}Random float

See mockd help templating for the complete list.


version: "1.0"
serverConfig:
httpPort: 4280
adminPort: 4290
logRequests: true
mocks:
# HTTP mock
- id: health-check
name: Health Check
type: http
enabled: true
http:
matcher:
method: GET
path: /health
response:
statusCode: 200
body: '{"status": "ok"}'
# HTTP with path parameters
- id: get-user
name: Get User
type: http
enabled: true
http:
matcher:
method: GET
path: /api/users/{id}
response:
statusCode: 200
headers:
Content-Type: application/json
body: |
{
"id": "{{request.pathParam.id}}",
"name": "User {{request.pathParam.id}}"
}
# WebSocket
- id: ws-echo
name: Echo WebSocket
type: websocket
enabled: true
websocket:
path: /ws/echo
echoMode: true
# GraphQL
- id: graphql
name: GraphQL API
type: graphql
enabled: true
graphql:
path: /graphql
introspection: true
schema: |
type Query {
hello: String!
}
resolvers:
Query.hello:
response: "Hello, World!"
statefulResources:
- name: posts
basePath: /api/posts
seedData:
- id: "1"
title: "First Post"
content: "Hello, World!"
  • CLI Reference - Command-line options
  • Request Matching - Matching patterns
  • mockd help config - Built-in configuration help
  • mockd help templating - Template variable reference
  • mockd init --template list - Available templates