HTTP Traffic Recording, Mocking, and Proxying for Connect
raw JSON →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.
Common errors
error TypeError: Cannot read properties of undefined (reading 'use') ↓
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' ↓
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. ↓
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. Warnings
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. ↓
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. ↓
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. ↓
Install
npm install connect-prism yarn add connect-prism pnpm add connect-prism Imports
- prism wrong
import prism from 'connect-prism';correctconst prism = require('connect-prism'); - create wrong
const prismInstance = new prism();correctconst config = prism.create({ name: 'myApi', context: '/api', host: 'localhost', port: 8000 }); - middleware wrong
app.use(prism);correctapp.use(prism.middleware);
Quickstart
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.');
});