HTTP Traffic Recording, Mocking, and Proxying for Connect

raw JSON →
1.0.21 verified Thu Apr 23 auth: no javascript abandoned

Connect-prism is a Node.js middleware designed to record, mock, and proxy HTTP traffic, primarily for front-end development and end-to-end testing of Single Page Applications (SPAs). It functions by integrating with the `connect` middleware framework, allowing developers to capture API responses, store them as JSON files, and then replay them locally, effectively caching backend interactions. The package supports four modes: 'record' (captures live responses), 'mock' (serves recorded responses), 'mock & record' (prioritizes mocks, records if not found), and 'proxy' (forwards requests to a target API). The current stable version, 1.0.21, was last published in early 2019, indicating an abandoned or minimally maintained status. Its key differentiators include its tight integration with `connect` servers for in-development mocking and its VCR-like approach to HTTP interaction capture, accelerating test suites and reducing reliance on live backend services during development. It decompresses gzipped/deflated responses for readable mock files.

error TypeError: Cannot read properties of undefined (reading 'use')
cause This error typically occurs when attempting to use connect-prism's middleware without properly initializing a `connect` application or if `prism.middleware` is not correctly invoked after `prism.create()`.
fix
Ensure you have const connect = require('connect'); and const app = connect(); and that app.use(prism.middleware); is called after prism.create({ ... });.
error Error: EACCES: permission denied, open '/path/to/mocks/generated-mock-file.json'
cause The Node.js process does not have sufficient write permissions to the directory specified in `mocksPath` or its subdirectories, preventing connect-prism from saving recorded mocks.
fix
Check and adjust the file system permissions for your mocksPath directory. For example, chmod -R 777 /path/to/mocks (for development, be cautious in production) or ensure the user running the Node.js application owns the directory.
error Prism is not proxying requests or recording mocks as expected.
cause This often happens due to incorrect configuration of `context`, `host`, `port`, or `https` in `prism.create()`, or the `connect-prism` middleware is not placed correctly in the `connect` server's middleware chain.
fix
Double-check the context path to ensure it matches the API endpoint your application is calling. Verify host, port, and https settings accurately reflect the target API. Ensure app.use(prism.middleware); is positioned early enough in your connect middleware stack to intercept API requests.
breaking The package connect-prism is abandoned, with the last update over 7 years ago (v1.0.21 in Feb 2019). It targets Node.js >= 0.10.0 and relies on the `connect` framework, which may have compatibility issues with modern Node.js versions (e.g., 16+) or ESM-only projects. Expect no further updates, bug fixes, or security patches.
fix Consider migrating to actively maintained HTTP mocking libraries such as 'nock' (for Node.js tests) or 'MSW' (Mock Service Worker for browser/Node.js) which offer broader compatibility and active development.
gotcha When using 'record' or 'mockrecord' modes, `connect-prism` writes mock files to the `mocksPath` directory. Ensure the Node.js process has appropriate write permissions to this directory, or recording will fail silently or with file system errors.
fix Verify directory permissions (`chmod 755 <mocks_path>`) and ensure the `mocksPath` configured exists and is writable by the user running the Node.js process.
gotcha The default mock file name generation for `connect-prism` is based on the request URL and headers. Small changes in request parameters or headers (e.g., query strings, user-agent) can lead to different mock files being generated or existing mocks not being found.
fix For consistent mock usage, normalize requests where possible, or use the 'override' feature if manual control over mock responses for specific request variations is needed. Regularly review generated mock files to ensure desired behavior.
npm install connect-prism
yarn add connect-prism
pnpm add connect-prism

This quickstart sets up a basic `connect` server with `connect-prism` middleware. It demonstrates how to configure prism to proxy requests to an external API (JSONPlaceholder), record responses to a local 'mocks' directory, or serve previously recorded mocks. It uses environment variables to switch between 'record' and 'mock' modes.

const connect = require('connect');
const http = require('http');
const path = require('path');
const prism = require('connect-prism');
const serveStatic = require('serve-static');

const app = connect();
const MOCKS_DIR = path.join(__dirname, 'mocks');

// Configure connect-prism for an API endpoint
// In 'record' mode, it will save responses to MOCKS_DIR
// In 'mock' mode, it will serve responses from MOCKS_DIR
prism.create({
  name: 'myApi',
  context: '/api',
  host: 'jsonplaceholder.typicode.com',
  port: 443,
  https: true,
  mode: process.env.PRISM_MODE || 'mock', // 'record', 'mock', 'proxy', 'mockrecord'
  mocksPath: MOCKS_DIR,
  // Optional: clear mocks on start in record/mockrecord modes
  clearOnStart: process.env.PRISM_MODE === 'record' || process.env.PRISM_MODE === 'mockrecord',
  // Log verbosity
  verbose: true
});

// Add connect-prism middleware to the connect app
app.use(prism.middleware);

// Serve static files (e.g., your SPA index.html)
app.use(serveStatic(path.join(__dirname, 'public')));

// Example: create a simple public/index.html for demonstration
// <!-- public/index.html -->
// <script>
//   fetch('/api/todos/1')
//     .then(res => res.json())
//     .then(data => console.log('API Response:', data))
//     .catch(err => console.error('Fetch Error:', err));
// </script>

http.createServer(app).listen(3000, () => {
  console.log('Connect-prism server running on http://localhost:3000');
  console.log(`Prism mode: ${process.env.PRISM_MODE || 'mock'}`);
  console.log(`Mocks directory: ${MOCKS_DIR}`);
  console.log('To record: set PRISM_MODE=record, then access /api/todos/1 in browser.');
  console.log('To mock: set PRISM_MODE=mock, ensure mocks are in place, then access /api/todos/1.');
});