A mock WebSocket server inspired by json-server that makes it easy to simulate real-time WebSocket APIs for development and testing.
Please note this is a placeholder, the package has not been published yet.
# Install globally
npm install -g json-ws-server
# Create events.json
echo '{
"config": {
"port": 4000,
"log": true
},
"events": [
{
"name": "welcome",
"trigger": "onConnect",
"payload": {
"event": "welcome",
"message": "Welcome!",
"time": "{{faker.date.recent}}"
}
}
]
}' > events.json
# Start the server
json-ws-server startnpm install -g json-ws-servernpm install json-ws-server# Start with default events.json
json-ws-server start
# Start with custom config file
json-ws-server start ./path/to/config.json
# In development (if installed locally)
npx json-ws-server startconst { createServer, loadConfig } = require('json-ws-server');
const { config, events } = loadConfig('./events.json');
createServer(config, events);Create an events.json file to define your mock WebSocket behavior:
{
"config": {
"port": 4000,
"path": "/ws",
"log": true,
"broadcastDefault": false,
},
"events": [
// Event definitions go here
]
}| option | type | default | description |
|---|---|---|---|
port |
number | required | Port to listen on |
path |
string | "/ws" | Websocket endpoint path |
log |
boolean | true | enable/disable logging |
broadcastDefault |
boolean | false | Default broadcast behavior for messages |
Define events that trigger specific behaviors when clients connect, send messages, or on intervals.
{
"name": "eventName",
"trigger": "onConnect|onMessage|interval",
"match": { /* for onMessage triggers */ },
"payload": { /* data to send */ },
"reply": true,
"broadcast": false,
"intervalMs": 5000
}| Property | Type | Required | Description |
|---|---|---|---|
name |
string | No | Event identifier for logging |
trigger |
string | Yes | When to trigger (onConnect, onMessage, interval) |
match |
object | No* | Message matching criteria (required for onMessage) |
payload |
any | Yes | Data to send (supports placeholders) |
reply |
boolean | No | Reply to sender (default: false) |
broadcast |
boolean | No | Broadcast to all clients (default: false) |
intervalMs |
number | No* | Interval in ms (required for interval) |
Triggered when a client connects to the WebSocket server.
{
"name": "welcome",
"trigger": "onConnect",
"payload": {
"event": "welcome",
"message": "Welcome to the server!",
"userId": "{{faker.string.uuid}}",
"timestamp": "{{faker.date.recent}}"
}
}Triggered when a client sends a message that matches the criteria.
{
"name": "getUser",
"trigger": "onMessage",
"match": {
"event": "getUser"
},
"payload": {
"event": "userResponse",
"id": "{{params.id}}",
"name": "{{faker.person.fullName}}",
"email": "{{faker.internet.email}}"
},
"reply": true
}Triggered at regular intervals to all connected clients.
{
"name": "heartbeat",
"trigger": "interval",
"intervalMs": 5000,
"payload": {
"event": "ping",
"timestamp": "{{faker.date.recent}}",
}
}You can use {{...}} placeholder syntax within your payload templates to generate dynamic content. This allows you to insert data from incoming parameters or generate realistic, random data on the fly.
There are two types of placeholders supported:
{{params.key}}
Use this syntax to access values from the trigger's parameters. This is the primary way to pass data from an incoming event into your payload. {{params.username}} will be replaced by the value of the username key in the parameters object. {{params.text}} will be replaced by the value of the text key.
{
"name": "chatMessage",
"trigger": "onMessage",
"match": {
"event": "sendMessage"
},
"payload": {
"event": "newMessage",
"from": "{{params.username}}",
"message": "{{params.text}}",
},
"broadcast": true
}{{faker.namespace.method}}
Leverage the powerful faker.js library to generate a vast range of realistic mock data directly in your payloads. This is incredibly useful for creating unique identifiers, timestamps, and rich content for testing or development.
The syntax directly maps to the faker API.
Common Examples:
{{faker.string.uuid}}β Generates a new UUID.{{faker.internet.email}}β Generates a random email address.{{faker.person.fullName}}β Generates a random full name.{{faker.date.recent}}β Generates a recent ISO date string.{{faker.lorem.sentence}}β Generates a random sentence.
For a complete list of all available methods, please consult the official Faker.js API Documentation.
{
"name": "chatMessage",
"trigger": "onMessage",
"match": {
"event": "sendMessage"
},
"payload": {
"event": "newMessage",
"from": "{{faker.internet.username}}",
"message": "{{faker.lorem.sentence}}",
},
"broadcast": true
}Click to expand complete `events.json` example.
{
"config": {
"port": 4000,
"log": true,
"broadcastDefault": false
},
"events": [
{
"name": "welcome",
"trigger": "onConnect",
"payload": {
"event": "welcome",
"message": "Welcome to mock-ws-server",
"time": "{{faker.date.recent}}",
"userId": "{{faker.string.uuid}}"
}
},
{
"name": "ping",
"trigger": "interval",
"intervalMs": 5000,
"payload": {
"event": "ping",
"timestamp": "{{faker.date.recent}}"
}
},
{
"name": "getUser",
"trigger": "onMessage",
"match": {
"event": "getUser"
},
"payload": {
"event": "userResponse",
"id": "{{params.id}}",
"name": "{{faker.person.fullName}}",
"email": "{{faker.internet.email}}"
},
"reply": true
},
{
"name": "chatMessage",
"trigger": "onMessage",
"match": {
"event": "chatMessage"
},
"payload": {
"event": "chatMessage",
"from": "{{params.username}}",
"message": "{{params.message}}",
"time": "{{faker.date.soon}}"
},
"broadcast": true
}
]
}// Using socket.io-client
const io = require('socket.io-client');
const socket = io('ws://localhost:4000', {
path: '/ws'
});
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('welcome', (data) => {
console.log('Welcome message:', data);
});
socket.on('ping', (data) => {
console.log('Server ping:', data);
});
// Request user data
socket.emit('getUser', { event: 'getUser', id: 123 });
socket.on('userResponse', (data) => {
console.log('User data:', data);
});
// Send a chat message
socket.emit('chatMessage', {
event: 'chatMessage',
username: 'Alice',
message: 'Hello everyone!'
});git clone <repository>
cd json-ws-server
npm install# Run in development mode
npm run dev
# Build for production
npm run build
# Run built version
npm start
# Run with custom config
npm run dev ./path/to/events.jsonsrc/
βββ bin/ # CLI entry point
βββ config/ # Configuration loading
βββ events/ # Event handling and parsing
βββ placeholders/ # Dynamic placeholder functions
βββ server/ # Server creation and setup
βββ utils/ # Utility functionsjson-ws-server start [config]Start the WebSocket server with the given configuration file.
loadConfig(filePath: string): Load and validate configuration from a JSON file.createServer(config: ServerConfig, events: EventDefinition[]): Create and start the WebSocket server.
- Ensure the port is not in use
- Check that your
events.jsonis valid JSON - Verify required fields are present in config
- Check that match criteria exactly match incoming messages
- Verify event names and triggers are correct
- Enable logging to see what's happening
- Verify the WebSocket path matches client configuration
- Check CORS settings if connecting from browser
- Ensure the server is running on the expected port
Enable logging in your config to debug issues:
{
"config": {
"port": 4000,
"log": true
}
}- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
MIT License - see LICENSE file for details.
- Inspired by json-server
- Built with Socket.IO
- Data generated with Faker.js
Made with β€οΈ for WebSocket developers