0
# Mock Server Setup
1
2
Core server lifecycle management, configuration, and metadata access for creating and controlling Mockttp instances.
3
4
## Capabilities
5
6
### Server Factory Functions
7
8
Creates different types of Mockttp instances for various use cases.
9
10
```typescript { .api }
11
/**
12
* Get a Mockttp instance on the local machine.
13
* In Node.js, creates an in-process MockttpServer.
14
* In browsers, creates a MockttpClient that connects to an admin server.
15
*/
16
function getLocal(options?: MockttpOptions): Mockttp;
17
18
/**
19
* Get a Mockttp instance controlled through a remote admin server.
20
* Connects to a Mockttp admin server to create and manage mock servers.
21
*/
22
function getRemote(options?: MockttpClientOptions): Mockttp;
23
24
/**
25
* Get a Mockttp admin server instance for managing multiple mock servers.
26
* Used for programmatic admin server setup or with browser-based testing.
27
*/
28
function getAdminServer(options?: MockttpAdminServerOptions): MockttpAdminServer;
29
30
/**
31
* Reset connections to admin servers.
32
* Useful for cleaning up connections in test teardown.
33
*/
34
function resetAdminServer(): void;
35
```
36
37
**Usage Examples:**
38
39
```typescript
40
import { getLocal, getRemote, getAdminServer } from "mockttp";
41
42
// Local server (most common for Node.js testing)
43
const mockServer = getLocal({
44
cors: false,
45
debug: true,
46
https: {
47
keyLength: 2048
48
}
49
});
50
51
// Remote client (for browser testing)
52
const mockClient = getRemote({
53
host: 'localhost',
54
port: 45454
55
});
56
57
// Admin server (for coordinating multiple instances)
58
const adminServer = getAdminServer({
59
port: 45454,
60
cors: true
61
});
62
```
63
64
### Server Lifecycle
65
66
Core methods for starting, stopping, and controlling mock servers.
67
68
```typescript { .api }
69
interface Mockttp {
70
/**
71
* Start the mock server on the specified port or port range.
72
* If no port specified, uses a random available port.
73
*/
74
start(port?: number | PortRange): Promise<void>;
75
76
/**
77
* Stop the mock server and reset all rules and subscriptions.
78
*/
79
stop(): Promise<void>;
80
81
/**
82
* Enable debug output for troubleshooting request matching and handling.
83
*/
84
enableDebug(): void;
85
86
/**
87
* Reset stored rules and subscriptions without stopping the server.
88
* Most cases should use stop() and start() instead.
89
*/
90
reset(): void;
91
}
92
93
type PortRange = { startPort: number, endPort: number };
94
```
95
96
**Usage Examples:**
97
98
```typescript
99
import { getLocal } from "mockttp";
100
101
const mockServer = getLocal();
102
103
// Start on random port
104
await mockServer.start();
105
console.log(`Server running on ${mockServer.url}`);
106
107
// Start on specific port
108
await mockServer.start(8080);
109
110
// Start with port range
111
await mockServer.start({ startPort: 8000, endPort: 8100 });
112
113
// Enable debugging
114
mockServer.enableDebug();
115
116
// Clean shutdown
117
await mockServer.stop();
118
```
119
120
### Server Metadata
121
122
Properties for accessing server information and generating URLs.
123
124
```typescript { .api }
125
interface Mockttp {
126
/**
127
* The root URL of the running server.
128
* Throws error if accessed before server is started.
129
*/
130
readonly url: string;
131
132
/**
133
* The port number the server is running on.
134
* Throws error if accessed before server is started.
135
*/
136
readonly port: number;
137
138
/**
139
* Environment variables for using the server as an HTTP/HTTPS proxy.
140
* Throws error if accessed before server is started.
141
*/
142
readonly proxyEnv: ProxyEnvConfig;
143
144
/**
145
* Generate a full URL for the given path on this server.
146
* Throws error if accessed before server is started.
147
*/
148
urlFor(path: string): string;
149
}
150
151
interface ProxyEnvConfig {
152
HTTP_PROXY: string;
153
HTTPS_PROXY: string;
154
}
155
```
156
157
**Usage Examples:**
158
159
```typescript
160
import { getLocal } from "mockttp";
161
162
const mockServer = getLocal();
163
await mockServer.start();
164
165
// Access server metadata
166
console.log(`Server URL: ${mockServer.url}`);
167
console.log(`Server port: ${mockServer.port}`);
168
console.log(`API endpoint: ${mockServer.urlFor('/api/users')}`);
169
170
// Use as proxy
171
process.env = { ...process.env, ...mockServer.proxyEnv };
172
173
// Now HTTP requests will be proxied through the mock server
174
```
175
176
### Configuration Options
177
178
Configuration interfaces for customizing server behavior.
179
180
```typescript { .api }
181
interface MockttpOptions {
182
/**
183
* CORS configuration.
184
* Defaults to false for local servers, true for remote clients.
185
*/
186
cors?: boolean | cors.CorsOptions;
187
188
/**
189
* Enable debug output for request matching and handling.
190
*/
191
debug?: boolean;
192
193
/**
194
* HTTPS configuration for TLS interception and certificate management.
195
*/
196
https?: MockttpHttpsOptions;
197
198
/**
199
* HTTP/2 support configuration.
200
* true: use HTTP/2 for all supporting clients
201
* 'fallback': use HTTP/2 only for clients that don't support HTTP/1.1
202
* false: never use HTTP/2
203
*/
204
http2?: true | 'fallback' | false;
205
206
/**
207
* SOCKS proxy support for unwrapping SOCKS connections.
208
*/
209
socks?: boolean | SocksServerOptions;
210
211
/**
212
* Protocol passthrough rules for non-HTTP traffic.
213
* 'unknown-protocol': pass through unrecognized protocols
214
*/
215
passthrough?: Array<'unknown-protocol'>;
216
217
/**
218
* Show suggested Mockttp code for unmatched requests.
219
* Useful for development but may confuse end users.
220
*/
221
suggestChanges?: boolean;
222
223
/**
224
* Record traffic for getSeenRequests() method.
225
* Set to false for high-traffic scenarios to save memory.
226
*/
227
recordTraffic?: boolean;
228
229
/**
230
* Maximum body size to process in bytes.
231
* Larger bodies become empty and won't match body matchers.
232
*/
233
maxBodySize?: number;
234
}
235
236
interface MockttpHttpsOptions {
237
/**
238
* CA certificate for signing generated certificates.
239
*/
240
ca?: string | Buffer;
241
242
/**
243
* Server certificate for HTTPS connections.
244
*/
245
cert?: string | Buffer;
246
247
/**
248
* Private key for HTTPS connections.
249
*/
250
key?: string | Buffer;
251
252
/**
253
* Path to certificate file (alternative to cert).
254
*/
255
certPath?: string;
256
257
/**
258
* Path to private key file (alternative to key).
259
*/
260
keyPath?: string;
261
262
/**
263
* Key length for generated certificates (default: 2048).
264
*/
265
keyLength?: number;
266
267
/**
268
* Default domain for non-SNI TLS connections.
269
*/
270
defaultDomain?: string;
271
272
/**
273
* Hostnames to pass through without TLS interception.
274
* Wildcards supported: '*.example.com'
275
*/
276
tlsPassthrough?: Array<{hostname: string}>;
277
278
/**
279
* Only intercept TLS for these hostnames, pass through all others.
280
* Mutually exclusive with tlsPassthrough.
281
*/
282
tlsInterceptOnly?: Array<{hostname: string}>;
283
284
/**
285
* TLS server configuration options.
286
*/
287
tlsServerOptions?: {
288
minVersion?: 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1';
289
};
290
}
291
292
interface MockttpClientOptions {
293
/**
294
* Admin server hostname (default: 'localhost').
295
*/
296
host?: string;
297
298
/**
299
* Admin server port (default: 45454).
300
*/
301
port?: number;
302
303
/**
304
* Use HTTPS for admin server connection.
305
*/
306
https?: boolean;
307
}
308
309
interface MockttpAdminServerOptions {
310
/**
311
* Host to bind the admin server (default: 'localhost').
312
*/
313
host?: string;
314
315
/**
316
* Port for the admin server (default: 45454).
317
*/
318
port?: number;
319
320
/**
321
* CORS configuration for admin endpoints.
322
*/
323
cors?: boolean | cors.CorsOptions;
324
325
/**
326
* Enable debug output for admin server operations.
327
*/
328
debug?: boolean;
329
}
330
```
331
332
**Usage Examples:**
333
334
```typescript
335
import { getLocal, getAdminServer } from "mockttp";
336
337
// Complex HTTPS configuration
338
const httpsServer = getLocal({
339
debug: true,
340
https: {
341
keyLength: 4096,
342
defaultDomain: 'localhost',
343
tlsPassthrough: [
344
{ hostname: '*.googleapis.com' },
345
{ hostname: 'secure-api.example.com' }
346
],
347
tlsServerOptions: {
348
minVersion: 'TLSv1.2'
349
}
350
},
351
http2: 'fallback',
352
cors: {
353
origin: ['http://localhost:3000', 'https://app.example.com'],
354
credentials: true
355
},
356
maxBodySize: 1024 * 1024 * 10 // 10MB
357
});
358
359
await httpsServer.start();
360
361
// Admin server for browser testing
362
const adminServer = getAdminServer({
363
port: 45455,
364
cors: true,
365
debug: true
366
});
367
368
await adminServer.start();
369
```
370
371
### SOCKS Configuration
372
373
```typescript { .api }
374
interface SocksServerOptions {
375
/**
376
* Authentication methods to accept.
377
* Current supported methods depend on implementation.
378
*/
379
authMethods?: string[];
380
}
381
```
382
383
### Constants
384
385
```typescript { .api }
386
/**
387
* Default port for Mockttp admin servers.
388
*/
389
const DEFAULT_ADMIN_SERVER_PORT = 45454;
390
```