Skip to main content

Custom Mocky Balboa server integration

If you need a custom integration for Mocky Balboa, you can use the @mocky-balboa/server package to create a custom wrapper for your application server. There are two main points to consider:

  1. Starting the Mocky Balboa server on the same process as your application server. This is how Mock Service Worker can intercept network requests on your application server.
  2. Ensuring you run your servers request handler within the AsyncLocalStorage context provided by the @mocky-balboa/server package.

Installation

pnpm add -D @mocky-balboa/server

Starting the server

Ensure you start the Mocky Balboa server on the same process as your application server.

import {
startServer,
} from "@mocky-balboa/server";

await startServer();

Running your handler in the AsyncLocalStorage context

To ensure the server can identify the client who initiated the request to your server, you need to run your server's HTTP handler within the AsyncLocalStorage context provided by the @mocky-balboa/server package.

import {
clientIdentityStorage,
ClientIdentityStorageHeader,
UnsetClientIdentity,
} from "@mocky-balboa/server";
import {
createServer
} from "node:http";

createServer((req, res) => {
// Get the client identity from the incoming request headers
let clientIdentity = req.headers[ClientIdentityStorageHeader];

if (typeof clientIdentity !== "string") {
// Fallback value when the client identity is not provided, you won't be able to identify the client
// and mock network requests
clientIdentity = UnsetClientIdentity;
}

return clientIdentityStorage.run(clientIdentity, () => {
// Call application handler here
});
});

API reference

Vite plugin

If you are only wanting to integrate with a Vite development server, you can use the @mocky-balboa/vite package for the Vite plugin.

import { defineConfig } from "vite";
import mockyBalboa from "@mocky-balboa/react-router";

export default defineConfig({
plugins: [mockyBalboa()],
});

See @mocky-balboa/vite plugin API reference for available options.