Mocklantis Guide

Learn how to create mock servers, configure endpoints, and accelerate your development workflow

đŸ“ĻInstallation

Get Mocklantis up and running on your machine

1

Download the application

Visit the download page and select the version for your operating system (macOS, Windows, or Linux).

2

Install and launch

Follow the installation instructions for your platform. Once installed, launch Mocklantis from your applications folder.

3

First launch

On first launch, you'll see an empty workspace. You're ready to create your first mock server!

Getting Started

Mocklantis allows you to create mock servers in two ways: Default (blank server) or Import from OpenAPI (auto-generated from spec). Both methods are accessed through the same interface.

1

Open Create Server Modal

In the left sidebar, locate the Mock Servers section at the top. Click the + button next to "Mock Servers" to open the create server modal.

💡 The + button is always visible at the top of the sidebar, even when you have existing servers.

2

Choose Your Method

The modal has two tabs at the top. Select the method that fits your needs:

📋 Default (Blank Server)

Create an empty server and manually add endpoints one by one. Perfect for:

  • Building a mock API from scratch
  • Small projects with few endpoints
  • Custom test scenarios
  • Learning and experimenting

Required Fields:

Server Name

Example: "My API", "Test Server", "Auth Service"

A friendly name to identify your server.

Port

Example: 3000, 8080, 4200

The port your mock server will listen on (1-65535). Must be unique.

âš ī¸ Port Validation: If the port is already in use by another server, you'll see a warning and cannot proceed.

🚀 Import from OpenAPI

Auto-generate a complete mock server from an OpenAPI/Swagger specification. Perfect for:

  • Mocking existing APIs with documentation
  • Large projects with many endpoints
  • Team collaboration with shared specs
  • Quick prototyping from design specs

Three Import Methods:

1. URL

https://petstore.swagger.io/v2/swagger.json

Paste a public URL to an OpenAPI spec (JSON or YAML).

2. File

Upload a local OpenAPI file (.json, .yaml, .yml) from your computer.

3. Paste

Click "Open Editor" and paste your OpenAPI spec directly (JSON or YAML format).

Optional Fields:

Server Name (Optional)

Custom name for your server. If not provided, name is extracted from OpenAPI spec.

Port (Optional)

Custom port. If not provided, an available port is automatically assigned.

✨ Auto-Generated: All endpoints, paths, methods, parameters, request/response schemas, and example responses are automatically created from the spec!

3

Click "New Mock Server"

After filling in the required fields, click the "New Mock Server" button at the bottom of the modal.

Default Method: The server is created instantly and appears in the sidebar. It's not started automatically - you must add at least one endpoint first, then the "Start Server" button becomes active.

OpenAPI Import: Processing may take a few seconds depending on spec size. The server is created with all endpoints and automatically starts - ready to use immediately!

4

Add Endpoints (Default servers only)

If you created a Default server, it starts empty. You need to add endpoints manually.

How to Add Endpoints:

  1. Click your server in the sidebar to select it
  2. In the main area, click the "+ New Endpoint" button (or the dropdown arrow next to it)
  3. Choose endpoint type:
    • HTTP - REST API endpoints (GET, POST, PUT, DELETE, etc.)
    • WebSocket - Real-time WebSocket endpoints
    • gRPC - Coming soon
    • GraphQL - Coming soon
  4. Configure your endpoint (path, method, response, etc.)
  5. Changes auto-save - no need to click save!

âš ī¸ Important: Servers cannot be started without at least one endpoint. Add an endpoint before clicking "Start Server".

5

Start Your Server

Once your server has at least one endpoint, click the "Start Server" button in the top section.

✅ Server Running

  • Status indicator turns green and pulsing
  • Button changes to "Stop Server"
  • Your mock API is now live and ready to receive requests!

💡 Hot Reload: You can edit endpoints while the server is running. Changes take effect immediately without restarting!

6

Test Your Mock API

Your mock server is now running! Test it with any HTTP client:

Example with cURL:

curl http://localhost:3000/api/users

Other Tools:

  • Postman / Insomnia - REST client applications
  • Your App - Point your frontend/mobile app to localhost
  • Browser - Visit URLs directly for GET requests
  • HTTPie, wget, fetch - Command-line tools

📊 Real-time Logging

Open the Logs panel (bottom of the screen) to see all incoming requests in real-time. You can inspect request headers, body, query params, and responses in a Postman-style accordion view!

Proxy

What is Proxy?

Proxy feature allows you to forward unmatched requests to a real backend server. This is incredibly useful when you want to:

  • Mock only specific endpoints while keeping others live
  • Test your app with a mix of mock and real data
  • Gradually migrate from a real API to mocks (or vice versa)
  • Debug specific endpoints without affecting the entire API

How Does It Work?

🔴 Proxy OFF (Default)

When a request comes to an undefined endpoint:

Request: GET /users/123
Response: {"error": "No mock matched"}

đŸŸĸ Proxy ON

When a request comes to an undefined endpoint:

Request: GET /users/123
→ Forwarded to: https://api.example.com/users/123
Response: (whatever the target API returns)

â„šī¸ If the target API also doesn't have this endpoint, it will return its own 404 error.

How to Use Proxy

Step 1: Open Proxy Settings

Click the Proxy OFF button (or Proxy ON if already enabled) in the server panel.

Step 2: Enable Proxy

Toggle the Enable Proxy switch to ON.

Step 3: Enter Target URL

Enter the URL of your real backend server. For example:

â€ĸ https://api.production.com
â€ĸ http://localhost:8080
â€ĸ https://staging.myapp.io

Step 4: Save & Restart

Click Save. If the server is running, it will automatically restart with the new proxy settings.

📚 Real-World Example

Scenario: Testing a Login Flow

You're building a mobile app and want to test the login flow. You want to mock the /auth/login endpoint to always return success, but keep all other endpoints (like /user/profile, /products) connected to the real backend.

1. Setup Mock Server
Server Port: 3000
Mock Endpoint: POST /auth/login
Response: {"success": true, "token": "mock-jwt-token"}
2. Enable Proxy
Proxy: ON
Target URL: https://api.myapp.com
3. Start Server & Test
Request: POST /auth/login
→ Returns mock response (always success)
Request: GET /user/profile
→ Forwarded to https://api.myapp.com/user/profile
→ Returns real user data
Request: GET /products
→ Forwarded to https://api.myapp.com/products
→ Returns real products

âš ī¸ Important Notes

  • â€ĸ Defined endpoints always take priority: Mock responses are returned first, proxy is only used for undefined endpoints.
  • â€ĸ Target URL must be accessible: Make sure the proxy target URL is reachable from your machine.
  • â€ĸ Headers are forwarded: Request headers (except Host) are automatically forwarded to the target server.
  • â€ĸ Response is passed through: Whatever the target server returns (including errors) is sent back to the client as-is.
  • â€ĸ Server restart required: When you change proxy settings, the server automatically restarts to apply changes.

Endpoints

Mocklantis supports two types of endpoints, each designed for different use cases. Create as many endpoints as you need - there are no limits!

🌐

HTTP/REST Endpoints

Traditional HTTP endpoints supporting all standard methods. Perfect for mocking REST APIs, webhooks, and any HTTP-based service.

Supported HTTP Methods

GETPOSTPUTDELETEPATCHHEADOPTIONS

Rich Features

  • ✓Path Variables: Typed parameters like /users/{id:number}
  • ✓Query Parameters: Type validation and exact value matching
  • ✓Request Matching: Match by headers, body, and query params
  • ✓Dynamic Responses: Use {{random.*}} variables for realistic data
  • ✓Custom Headers: Full control over request and response headers
  • ✓Response Delay: Simulate network latency in milliseconds

💡 REST Conventions? Optional!

While RESTful design is recommended for clean APIs, Mocklantis doesn't enforce it. You're free to structure your endpoints however you need:

  • ✅ RESTful: GET /users/123
  • ✅ RPC-style: POST /getUserById
  • ✅ Custom: GET /api/v1/fetch-user-data?id=123
  • ✅ Whatever works for your use case!

We're not strict - use the patterns that make sense for your project. Both REST purists and pragmatic developers are welcome here! 🤝

⚡

WebSocket Endpoints

Real-time bidirectional communication channels. Perfect for chat applications, live updates, notifications, and any real-time feature.

Four Powerful Modes

đŸ’Ŧ
CONVERSATIONAL

Pattern-based request/response. Client sends message, server responds based on matching patterns.

📡
STREAMING

Continuous data flow. Server sends messages at regular intervals automatically.

đŸŽ¯
TRIGGERED_STREAMING

Start streaming on demand. Client sends trigger message, server starts sending stream.

Advanced Features

  • ✓Message Patterns: Match incoming messages by exact, contains, regex, or JSON path
  • ✓Lifecycle Events: Custom messages on connect/disconnect
  • ✓Configurable Intervals: Control streaming frequency and timing
  • ✓Client Limits: Control maximum connected clients

Quick Comparison

FeatureHTTP/RESTWebSocket
Connection TypeRequest-ResponseBidirectional, Persistent
Best ForCRUD operations, APIsReal-time updates, chat, live data
Server PushNoYes
OverheadHigher (new connection each request)Lower (single persistent connection)

📚 Want to Learn More?

The sections above provide a quick overview of both endpoint types. For detailed guides with examples and best practices, continue reading below. We'll dive deep into HTTP/REST features, request matching, status codes, and much more!

HTTP/REST Endpoints

📊 HTTP Status Codes

Every HTTP endpoint can return any valid HTTP status code. Mocklantis supports all standard status codes from 200 to 599. Simply click on the status selector in the Response section to choose from popular codes like 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error, and more.

The status selector is searchable - you can type the code number or the status text to quickly find what you need. For example, search "unauthorized" to find 401, or search "403" to find Forbidden.

Tip: Use appropriate status codes to make your mocks realistic. Return 200 for successful operations, 201 for resource creation, 204 for deletions, 400 for validation errors, 404 for missing resources, and 500 for server errors.

📄 Request Body Matching

By default, Mocklantis returns your configured response regardless of what's in the request body. But sometimes you want different responses based on the request payload. That's where Request Body Matching comes in.

In the Request → Body tab, you'll find a "Match Body" checkbox. When enabled, Mocklantis will only return your mock response if the incoming request body matches what you specified (as JSON). This is perfect for testing different scenarios - for example, returning success for valid login credentials and error for invalid ones.

Example: Login endpoint with body matching
✓ Endpoint 1: POST /auth/login
Match Body: ON
Expected Body: {"email": "[email protected]", "password": "correct"}
Response: {"success": true, "token": "..."} (200)
✓ Endpoint 2: POST /auth/login
Match Body: OFF (catches everything else)
Response: {"success": false, "error": "Invalid credentials"} (401)

If no endpoint matches the request body, Mocklantis returns the first endpoint with "Match Body" disabled, or a 404 if all have matching enabled.

đŸˇī¸ Request Header Matching

Similar to body matching, you can also match requests based on their headers. In the Request → Headers tab, enable the "Match Headers" checkbox to require specific headers in the incoming request.

This is useful for testing authentication flows (matching Authorization headers), API versioning (matching Accept headers), or any scenario where different headers should trigger different responses.

Example: Protected endpoint
✓ Endpoint 1: GET /api/data
Match Headers: ON
Expected: Authorization: Bearer valid-token
Response: {"data": [...]} (200)
✓ Endpoint 2: GET /api/data
Match Headers: OFF
Response: {"error": "Unauthorized"} (401)

🔍 Query Parameter Matching

Query parameters can be validated in two ways: type validation and exact value matching. In the Request → Query Params tab, you can define expected query parameters and choose whether to match their type or exact value.

When "Match Query Params" is enabled, Mocklantis uses a scoring algorithm to find the best matching endpoint. Exact value matches score higher than type matches. If multiple endpoints match, the one with the highest score wins. This allows you to create generic fallback endpoints and specific ones for particular query parameter values.

Example: Search with filters
✓ Endpoint 1: GET /api/products
Match Query Params: ON
category = "electronics" (exact match)
Response: {"products": ["laptop", "phone", ...]}
✓ Endpoint 2: GET /api/products
Match Query Params: ON
category: string (type match - catches all other categories)
Response: {"products": [...]}

More details about query parameter types and validation can be found in the Query Parameters section below.

🎨 Automatic Content-Type Detection

Mocklantis automatically detects and sets the Content-Type header based on your request and response body content. When you type JSON in the body editor, it automatically adds Content-Type: application/json to the headers. The same works for XML content.

The Monaco editor (used for body editing) also provides syntax highlighting, validation, and formatting based on the detected content type. This makes it easy to work with JSON and XML responses without manually configuring everything.

âš™ī¸ Response Configuration

Each HTTP endpoint has a comprehensive response configuration. In the Response section, you can set:

  • Status Code: Any HTTP status from 200 to 599
  • Response Delay: Simulate network latency in milliseconds (0-60000ms)
  • Response Body: JSON, XML, plain text, or any content with syntax highlighting
  • Response Headers: Custom headers returned with the response

The response body supports dynamic variables using the {{random.*}} syntax. For example, {{random.number(1,100)}} generates a random number between 1 and 100 each time the endpoint is called. More details about random variables can be found in the Random Variables section below.

✨ Best Practices

  • â€ĸ Use realistic HTTP status codes to make your tests more reliable
  • â€ĸ Create multiple endpoints with different matching rules to simulate various scenarios
  • â€ĸ Use body matching sparingly - it's powerful but can make debugging harder if overused
  • â€ĸ Add response delays to test loading states and race conditions in your app
  • â€ĸ Leverage random variables to generate realistic dynamic data
  • â€ĸ Document your endpoints with descriptive paths and consistent naming

Path Variables

Path variables allow you to create dynamic endpoints that accept parameters in the URL. Use the format {paramName:type} to define typed parameters.

Example:

/users/{id:number}/posts/{slug:slug}

📍 How to Add Path Variables:

  1. Select your endpoint
  2. In the Path input field (top section), type your path with variables
  3. Use the format: /path/{variable:type}
  4. Example: /users/{id:number}
  5. Path variables are automatically validated on each request

🚀 Express.js Style (Alternative)

You can also use the popular Express.js style :paramName format:

/users/:id/posts/:postId

Note: This format doesn't support type validation. Use {id:type} format if you need type validation.

Tip: You can mix both formats: /users/:id/posts/{slug:slug}

Type Reference

TypeDescriptionValid ExamplesInvalid Examples
numberOnly digits (integers)123, 456, 78912abc, 12.5, abc
doubleDecimal numbers12.5, 123, 0.9912abc, abc
stringOnly letters (a-z, A-Z)john, abc, Hello123, abc123, john-doe
alphanumericLetters and digits onlyabc123, 12abc, User1abc-123, test_1, hello!
slugURL-friendly (letters, digits, hyphens, underscores)product-123, my_item, test-slugtest slug, item@123
emailEmail address format[email protected]test.com, @example.com
uuidUUID format (8-4-4-4-12)550e8400-e29b-41d4-a716-446655440000123, abc-def
anyAccepts any value (default)anything works-
custom regexAny regex pattern you define[A-Z]{2}\d{4}, \w{3,16}depends on pattern

Real-World Examples

User Management API

Endpoint:/users/{id:number}
Valid:/users/123
Invalid:/users/abc (returns 400)

Blog Posts

Endpoint:/posts/{slug:slug}/comments/{id:number}
Valid:/posts/my-first-post/comments/42
Invalid:/posts/my post/comments/abc

Session Verification

Endpoint:/sessions/{sessionId:uuid}
Valid:/sessions/550e8400-e29b-41d4-a716-446655440000
Invalid:/sessions/123

Custom Regex Patterns

Beyond built-in types, you can define custom regex patterns for advanced validation.

Simply use any regex pattern after the colon. If it's not a built-in type, it will be treated as a regex.

Country Code + Order ID

Pattern:{code:[A-Z]{2}\d{4}}(2 letters + 4 digits)
Endpoint:/orders/{code:[A-Z]{2}\d{4}}
Valid:/orders/TR1234, /orders/US9999
Invalid:/orders/tr1234, /orders/T1234, /orders/TR12

MD5 Hash

Pattern:{hash:[a-f0-9]{32}}(32 hex chars)
Endpoint:/files/{hash:[a-f0-9]{32}}
Valid:/files/5d41402abc4b2a76b9719d911017c592
Invalid:/files/abc123 (too short)

Semantic Version

Pattern:{version:\d+\.\d+\.\d+}(e.g., 1.2.3)
Endpoint:/api/{version:\d+\.\d+\.\d+}/users
Valid:/api/1.0.0/users, /api/2.15.3/users
Invalid:/api/v1/users, /api/1.0/users

Username with Length Constraint

Pattern:{username:\w{3,16}}(3-16 alphanumeric)
Endpoint:/profile/{username:\w{3,16}}
Valid:/profile/john_doe, /profile/user123
Invalid:/profile/jo (too short), /profile/verylongusername123

Pro Tips

💡

If you don't specify a type, it defaults to any

💡

Mix and match multiple path variables: /api/{v:number}/users/{name:string}

💡

Type validation happens at runtime - invalid requests return 400 Bad Request

💡

Use slug type for URL-friendly identifiers in your endpoints

đŸŽ¯

Custom regex patterns give you ultimate flexibility - any pattern not matching built-in types is treated as regex

đŸŽ¯

Remember to escape special regex characters: {version:\d+\.\d+} not {version:\d+.\d+}

Random Variables

Random variables allow you to generate dynamic, random data in your request and response bodies at runtime. Use the format {{random.type}} in your response body.

Example Request Body & Response Body:

{
  "id": "{{random.uuid}}",
  "email": "{{random.email}}",
  "name": "{{random.name}}",
  "age": {{random.number}},
  "ipAddress": "{{random.ip}}",
  "createdAt": "{{random.date}}"
}

Actual Request & Response (Example):

{
  "id": "a3d5f7b9-1234-5678-9abc-def012345678",
  "email": "[email protected]",
  "name": "Alice Johnson",
  "age": 7845,
  "ipAddress": "192.168.1.147",
  "createdAt": "2024-08-15"
}

âš ī¸ Important: Quotes for String Types

String types (uuid, email, name, ip, url, website, date, string, alphanumeric, custom) must be wrapped in quotes in JSON. Number types (number, double) and boolean should NOT have quotes.

✅ Correct:"ip": "{{random.ip}}"
✅ Correct:"age": {{random.number}}
❌ Wrong:"ip": {{random.ip}} (missing quotes)

Random Variable Types

TypeUsageExample OutputDefault Range/Limit
string{{random.string}}
{{random.string(30)}}
aBcDeFgHiJ10 chars (max 50)
uuid{{random.uuid}}550e8400-e29b-41d4...UUID v4 format
number{{random.number}}
{{random.number(1,100)}}
74820-999 (max 1,000,000)
double{{random.double}}
{{random.double(0.0,10.0)}}
342.780.0-100.0 (max 1,000,000, 2 decimals)
email{{random.email}}[email protected]RFC 2606 domains
name{{random.name}}John SmithFirst + Last name
boolean{{random.boolean}}truetrue or false
date{{random.date}}2024-11-03ISO format (last year)
phone{{random.phone}}+905123456789TR format
url{{random.url}}https://example.com/apiHTTPS URLs
ip{{random.ip}}192.168.1.147Private IP range
website{{random.website}}example.comDomain names only
alphanumeric{{random.alphanumeric}}
{{random.alphanumeric(20)}}
aB3dE9fG2h10 chars (max 50)
custom{{random.custom([A-Z]{3}\d{4})}}ABC1234Regex pattern (max 100)

Advanced Usage

Parameterized Random Types

String with custom length:

{{random.string(30)}}→ 30 character string

Number with range:

{{random.number(1,100)}}→ Number between 1 and 100

Double with range:

{{random.double(0.0,1.0)}}→ Decimal between 0.0 and 1.0

Custom Regex Patterns

✨ Supports Nested Parentheses!

Complex regex patterns with nested brackets like [A-Z]{3}\d{4} are fully supported.

Example Patterns:

{{random.custom([A-Z]{3}\d{4})}}→ ABC1234 (3 uppercase + 4 digits)
{{random.custom([a-f0-9]{32})}}→ MD5-like hash
{{random.custom(\d{3}-\d{2}-\d{4})}}→ 123-45-6789 (SSN format)

Complete Example

Request Body & Response Body Template:

{
  "userId": "{{random.uuid}}",
  "username": "{{random.alphanumeric(12)}}",
  "email": "{{random.email}}",
  "fullName": "{{random.name}}",
  "age": {{random.number(18,65)}},
  "score": {{random.double(0.0,100.0)}},
  "active": {{random.boolean}},
  "phone": "{{random.phone}}",
  "website": "{{random.website}}",
  "ipAddress": "{{random.ip}}",
  "registeredAt": "{{random.date}}",
  "token": "{{random.custom([A-Z0-9]{16})}}"
}

Real-World Use Cases

User Registration: Generate Realistic User Data

When testing user registration flows, you need unique user data for each request. Random variables make this effortless.

POST /api/register - Response Template
RESPONSE BODY (Template)
{
  "success": true,
  "user": {
    "id": "{{random.uuid}}",
    "username": "{{random.alphanumeric(12)}}",
    "email": "{{random.email}}",
    "fullName": "{{random.name}}",
    "phoneNumber": "{{random.phone}}",
    "createdAt": "{{random.date}}",
    "verified": {{random.boolean}}
  },
  "token": "{{random.custom([A-Za-z0-9]{64})}}"
}
ACTUAL RESPONSE (Example)
{
  "success": true,
  "user": {
    "id": "a3d5f7b9-1234-5678-9abc-def012345678",
    "username": "xK8mP2vQ7nT4",
    "email": "[email protected]",
    "fullName": "Sarah Williams",
    "phoneNumber": "+905123456789",
    "createdAt": "2024-08-15",
    "verified": true
  },
  "token": "Xy9Kp2Nm4Qr7Tv3Wz8Ys5Lt6Hu9Jn2Op1Kq4Rw7Sx8Yv3Zu6Kp9Ln2Mt5Qr8Tw1Xv4Yz"
}
Every request generates completely different user data - perfect for testing signup flows!

E-commerce: Dynamic Product Catalog

Generate realistic product catalogs with varying prices, stock levels, and ratings without hardcoding values.

GET /api/products - Response Template
RESPONSE BODY (Template)
{
  "products": [
    {
      "id": "{{random.uuid}}",
      "name": "Wireless Mouse",
      "sku": "{{random.custom([A-Z]{3}-\d{6})}}",
      "price": {{random.double(9.99,199.99)}},
      "stock": {{random.number(0,500)}},
      "rating": {{random.double(1.0,5.0)}},
      "inStock": {{random.boolean}},
      "url": "{{random.url}}"
    },
    {
      "id": "{{random.uuid}}",
      "name": "Mechanical Keyboard",
      "sku": "{{random.custom([A-Z]{3}-\d{6})}}",
      "price": {{random.double(49.99,299.99)}},
      "stock": {{random.number(0,200)}},
      "rating": {{random.double(1.0,5.0)}},
      "inStock": {{random.boolean}},
      "url": "{{random.url}}"
    }
  ],
  "total": {{random.number(50,500)}}
}
ACTUAL RESPONSE (Example)
{
  "products": [
    {
      "id": "b7c3d8e9-5678-1234-bcde-abc123456789",
      "name": "Wireless Mouse",
      "sku": "ABC-582941",
      "price": 34.79,
      "stock": 247,
      "rating": 4.37,
      "inStock": true,
      "url": "https://example.com/api/products/mouse"
    },
    {
      "id": "f2a8b4c6-9012-3456-defg-xyz987654321",
      "name": "Mechanical Keyboard",
      "sku": "XYZ-193847",
      "price": 129.99,
      "stock": 87,
      "rating": 3.84,
      "inStock": false,
      "url": "https://example.org/api/products/keyboard"
    }
  ],
  "total": 342
}
Test different price ranges, stock levels, and ratings with every request!

Analytics Dashboard: Metrics & Statistics

Simulate analytics dashboards with dynamic metrics, visitor counts, and performance data.

GET /api/dashboard/stats - Response Template
RESPONSE BODY (Template)
{
  "stats": {
    "totalUsers": {{random.number(10000,100000)}},
    "activeUsers": {{random.number(1000,10000)}},
    "revenue": {{random.double(50000.0,500000.0)}},
    "conversionRate": {{random.double(1.0,10.0)}},
    "avgSessionTime": {{random.number(120,600)}},
    "bounceRate": {{random.double(20.0,80.0)}}
  },
  "traffic": {
    "visitors": {{random.number(500,5000)}},
    "pageViews": {{random.number(1000,20000)}},
    "uniqueVisitors": {{random.number(300,3000)}}
  },
  "topPages": [
    {
      "url": "{{random.url}}",
      "views": {{random.number(100,5000)}}
    },
    {
      "url": "{{random.url}}",
      "views": {{random.number(100,5000)}}
    }
  ],
  "reportDate": "{{random.date}}"
}
Perfect for testing dashboard UI with varying metrics - see how your charts handle different data ranges!

Tips & Best Practices

✅

Random variables are replaced at runtime on each request

✅

Each request gets unique random values - perfect for testing

✅

Use parameterized types for controlled randomness

âš ī¸

All generated values respect maximum limits to prevent overflow

đŸŽ¯

Combine random variables with static data for realistic mock responses

đŸŽ¯

Email domains use RFC 2606 reserved domains (example.com, example.org, example.net)

âš ī¸

Remember: String types (ip, email, uuid, etc.) need quotes in JSON. Number/boolean types don't!

💡

Use custom regex patterns for industry-specific formats like order IDs, tracking numbers, or license keys

Response Templating

Response templating allows you to reference incoming request data in your response body. Use the format {{request.category.key}} to include request values dynamically.

Available Variables:

CategorySyntaxDescriptionKey Required
path{{request.path.id}}Path parameter valueYes
query{{request.query.name}}Query parameter valueYes
header{{request.header.X-Request-Id}}Request header (case-insensitive)Yes
body{{request.body}}
{{request.body.user.name}}
Full body or field path (JSON/XML)Optional
method{{request.method}}HTTP method (GET, POST, etc.)No
url{{request.url}}Full request URLNo
timestamp{{request.timestamp}}ISO timestamp of requestNo

Path Parameters

GET /users/{id:number}

RESPONSE TEMPLATE

{
  "userId": "{{request.path.id}}",
  "message": "User {{request.path.id}} found",
  "requestedAt": "{{request.timestamp}}"
}

REQUEST: GET /users/42

ACTUAL RESPONSE

{
  "userId": "42",
  "message": "User 42 found",
  "requestedAt": "2024-01-15T10:30:00.000Z"
}

JSON Body & JSONPath

POST /api/users

REQUEST BODY (JSON)

{
  "user": {
    "name": "John Doe",
    "email": "[email protected]"
  },
  "role": "admin"
}

RESPONSE TEMPLATE

{
  "status": "created",
  "userName": "{{request.body.user.name}}",
  "userEmail": "{{request.body.user.email}}",
  "assignedRole": "{{request.body.role}}"
}

ACTUAL RESPONSE

{
  "status": "created",
  "userName": "John Doe",
  "userEmail": "[email protected]",
  "assignedRole": "admin"
}

JSONPath Syntax

user.name - Nested object access
items[0] - Array index access
items[0].product - Nested array access

XML Body & XPath

When the request body is XML (Content-Type: application/xml), you can extract fields using XPath-like dot notation.

POST /api/orders (XML)

REQUEST BODY (XML)

<order>
  <customer>
    <name>John Doe</name>
    <email>[email protected]</email>
  </customer>
  <total>150.00</total>
</order>

RESPONSE TEMPLATE

{
  "orderId": "{{random.uuid}}",
  "customerName": "{{request.body.order.customer.name}}",
  "customerEmail": "{{request.body.order.customer.email}}",
  "orderTotal": "{{request.body.order.total}}"
}

ACTUAL RESPONSE

{
  "orderId": "a1b2c3d4-5678-90ab-cdef-ghij12345678",
  "customerName": "John Doe",
  "customerEmail": "[email protected]",
  "orderTotal": "150.00"
}

XPath Syntax

order.customer.name - Nested element access
users.user.id - Deep nested access
/order/total - Full XPath also supported

Content-Type Detection

Field extraction uses the Content-Type header to determine the parser:

  • application/json → JSONPath
  • application/xml or text/xml → XPath
  • text/plain → No field extraction (use {{request.body}} for full body)

Pro Tips

💡

Combine with random variables: {"id": "{{random.uuid}}", "user": "{{request.body.name}}"}

💡

Use {{request.body}} without a path to echo the entire request body

💡

Headers are case-insensitive: {{request.header.content-type}} works the same as {{request.header.Content-Type}}

💡

Missing values return empty string - your response won't break if a field doesn't exist

Headers

Request Headers

Validate incoming request headers to ensure clients send the correct headers. Enable Match Request Headers toggle to activate validation.

📍 How to Add Request Headers:

  1. Select your endpoint
  2. Click on the Request tab
  3. Click on the Headers sub-tab
  4. Click + Add Header button
  5. Enter header name and expected value
  6. Enable Match Request Headers toggle

Example:

Authorization: Bearer token123
Content-Type: application/json

✓ Requests with matching headers → 200 OK
✗ Requests with missing/incorrect headers → 400 Bad Request

📘 Real World Examples: Content-Type Behavior

Mocklantis aims to provide a high-quality mocking experience by simulating real-world HTTP behavior. We automatically add Content-Type headers for your convenience, but our validation logic follows actual HTTP standards to ensure your mocks behave like production servers.

How it works: When you add a request body, Mocklantis automatically detects and sets the Content-Type (JSON, XML, HTML, or plain text). However, when validating incoming requests with Match Request Headers enabled, we follow real-world rules:

✅ Scenario 1: No Body → Content-Type Optional

GET /api/users

When there's no request body (common in GET, HEAD, DELETE), Content-Type is not validated. This matches how real HTTP servers behave - no body means Content-Type doesn't matter.

âš ī¸ Scenario 2: Body Present, No Content-Type → Error

POST /api/users
{"name": "James"}

If a request includes a body but no Content-Type header, validation fails with 400 Bad Request. This protects your mock endpoints from malformed requests, just like real production APIs.

✅ Scenario 3: Body + Content-Type → Perfect

POST /api/users
Content-Type: application/json

{"name": "David"}

A complete, well-formed request with proper Content-Type header passes validation successfully. This is the standard way HTTP clients (like Postman, fetch, axios) send requests.

Why this matters: By following real-world HTTP behavior, Mocklantis helps you catch integration issues early. If your client sends requests without proper headers, you'll discover it during development, not in production.

Response Headers

Add custom headers to your mock responses. Useful for CORS, caching, content-type, and more.

📍 How to Add Response Headers:

  1. Select your endpoint
  2. Click on the Response tab
  3. Click on the Headers sub-tab
  4. Click + Add Header button
  5. Enter header name and value

Common Examples:

Content-Type: application/json
Access-Control-Allow-Origin: *
Cache-Control: no-cache
X-Custom-Header: custom-value

Real-World Use Cases

Authentication: Bearer Token & API Keys

Test protected endpoints by validating authentication headers. Create multiple endpoints to simulate authenticated vs unauthenticated scenarios.

Endpoint 1: Authenticated Access
REQUEST HEADERS (Required)
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Enable "Match Request Headers" toggle
REQUEST
GET /api/profile
With Authorization header
RESPONSE (200 OK)
{
  "userId": "12345",
  "name": "John Doe",
  "email": "[email protected]"
}
Endpoint 2: Unauthenticated Access (Same Path)
REQUEST HEADERS
No Authorization header (or "Match Request Headers" disabled)
REQUEST
GET /api/profile
Without Authorization header
RESPONSE (401 Unauthorized)
{
  "error": "Unauthorized",
  "message": "Missing or invalid authentication token"
}

💡 How it Works:

Create two endpoints with the same path /api/profile. Endpoint 1 requires the Authorization header and returns user data. Endpoint 2 doesn't match headers and returns 401. Mocklantis automatically routes requests based on header presence!

CORS: Cross-Origin Resource Sharing

Test CORS behavior by adding appropriate response headers. Essential for frontend development with different origins.

CORS-Enabled Endpoint
RESPONSE HEADERS (Add these)
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
USE CASE

When your frontend (localhost:3000) calls your mock API (localhost:8021), browsers require CORS headers. Add these response headers to enable cross-origin requests.

âš ī¸ Preflight Requests:

Browsers send OPTIONS requests before actual requests for CORS. Create a separate OPTIONS endpoint with the same path and return 204 No Content with CORS headers to handle preflight requests.

API Versioning

Test different API versions by validating version headers or using path variables.

Version-Based Routing
OPTION 1: Header-Based Versioning
Request Header: Accept: application/vnd.myapi.v2+json
Create separate endpoints with different Accept headers
OPTION 2: Custom Version Header
Request Header: X-API-Version: 2.0
Enable "Match Request Headers" and set X-API-Version value
EXAMPLE
Endpoint 1: GET /api/users
Header: X-API-Version: 1.0
Response: Legacy format
Endpoint 2: GET /api/users
Header: X-API-Version: 2.0
Response: New format with extra fields

Content Negotiation: JSON vs XML

Return different response formats based on the Accept header.

Format-Based Response
JSON ENDPOINT
Request Header: Accept: application/json
Response Header: Content-Type: application/json
Response Body:
{"name": "John", "age": 30}
XML ENDPOINT (Same Path)
Request Header: Accept: application/xml
Response Header: Content-Type: application/xml
Response Body:
<user>
  <name>John</name>
  <age>30</age>
</user>

Rate Limiting Headers

Simulate rate limiting by returning appropriate headers in responses.

Response Headers for Rate Limiting
ADD THESE RESPONSE HEADERS
X-RateLimit-Limit: 100 (max requests per hour)
X-RateLimit-Remaining: 95 (remaining requests)
X-RateLimit-Reset: 1699891200 (reset timestamp)
Retry-After: 3600 (seconds until reset)
TEST SCENARIO

Create an endpoint that returns 429 Too Many Requests with these headers to test how your app handles rate limiting.

Caching & Cache Control

Control caching behavior with response headers.

Common Caching Scenarios
No Cache (Always Fresh)
Cache-Control: no-cache, no-store, must-revalidate
Cache for 1 Hour
Cache-Control: max-age=3600
Cache for 1 Day (Public)
Cache-Control: public, max-age=86400
Private Cache (User-Specific)
Cache-Control: private, max-age=3600

Pro Tips

💡

Request header validation is strict - headers must match exactly

💡

Response headers are sent with every response automatically

💡

Use response headers to simulate real API behavior (CORS, auth tokens, etc.)

✨

Create multiple endpoints with the same path but different header requirements to test authenticated vs unauthenticated flows

đŸŽ¯

Use header matching for API versioning - same path, different responses based on version header

Webhooks

Webhooks allow you to automatically trigger HTTP requests to external services when your mock endpoints are called. This enables you to simulate real-world integrations, test notification systems, and create realistic async workflows.

How it works:

Client Request → Mock Response Sent → Webhook Triggered (async)
                        ↓                       ↓
                   Immediate              External Service
                   Response               (Slack, Payment, etc.)

Key Features:

  • â€ĸ Fire-and-Forget: Webhooks execute asynchronously after the mock response is sent
  • â€ĸ Fully Isolated: Webhook failures never affect your mock endpoint responses
  • â€ĸ Template Variables: Extract values from the original request for your webhook payload

Creating a Webhook

📍 How to Create:

  1. Click the dropdown arrow â–ŧ next to the "+ New Endpoint" button in the header
  2. Select "Webhook" from the dropdown menu
  3. Give your webhook a descriptive name
  4. Configure the HTTP method and target URL
  5. Add headers and request body as needed
  6. Bind the webhook to one or more endpoints

âš ī¸ Important:

A webhook will only fire when it's bound to at least one endpoint. Unbound webhooks exist in your configuration but never execute.

Binding Webhooks to Endpoints

There are two ways to create a binding between a webhook and an endpoint:

Method 1: From the HTTP Endpoint (Hooks Tab)

  1. Select your HTTP endpoint in the sidebar
  2. Go to the "Hooks" tab in the body section
  3. You'll see a list of all available webhooks
  4. Click on a webhook to toggle its binding

Tip: Use the search box to filter webhooks. Click the external link icon to jump to webhook settings.

Method 2: From the Webhook Settings

  1. Select your webhook in the sidebar (orange "HOOK" badge)
  2. Find the "Trigger Endpoints" dropdown
  3. Search and select endpoints to bind
  4. One webhook can be bound to multiple endpoints

Tip: This method is useful when binding the same webhook to many endpoints at once.

Webhook Configuration

Request Settings

SettingDescription
MethodHTTP method (POST, PUT, GET, DELETE, PATCH, HEAD, OPTIONS)
URLTarget URL (http:// or https://)
HeadersCustom request headers (key-value pairs)
BodyRequest body with template variable support

Advanced Settings

SettingDefaultRangeDescription
Delay0 ms0-60000Wait time before sending
Timeout30000 ms1000-120000Max wait for response
Retry Count00-10Retry attempts on failure
Retry Delay1000 ms100-30000Wait between retries
Skip SSL Verifyfalse-Ignore SSL cert errors

Authentication

Mocklantis supports 4 authentication types:

None

No authentication headers. Use for public webhooks.

Basic Auth

Username & password encoded as Base64.

Authorization: Basic dXNlcjpwYXNz

Bearer Token

JWT or OAuth token in Authorization header.

Authorization: Bearer eyJhbGc...

API Key

Custom header or query parameter.

X-API-Key: your-api-key-here

Template Variables

Extract values from the original HTTP request and include them in your webhook payload using {{category.key}} syntax.

VariableExampleDescription
request.path.*{{request.path.id}}Path parameter (e.g., /users/:id)
request.query.*{{request.query.page}}Query parameter (e.g., ?page=1)
request.header.*{{request.header.X-User-Id}}Request header value
request.body{{request.body}}Entire request body as-is
request.body.*{{request.body.user.email}}JSONPath extraction from body
request.method{{request.method}}HTTP method (GET, POST, etc.)
request.url{{request.url}}Full URL path with query string
request.timestamp{{request.timestamp}}ISO-8601 timestamp
random.uuid{{random.uuid}}Random UUID v4
random.number{{random.number(1,100)}}Random number in range

JSONPath for Body Extraction:

{{request.body.user.name}} → Nested object: body.user.name
{{request.body.items[0]}} → Array index: first item
{{request.body.items[0].price}} → Nested in array: first item's price

Example webhook body:

{
  "event": "order_created",
  "timestamp": "{{request.timestamp}}",
  "data": {
    "orderId": "{{request.path.id}}",
    "customer": "{{request.body.customer.name}}",
    "total": {{request.body.total}}
  }
}

Real-World Use Cases

Sports: Live Match Score Updates

Simulate a sports API that notifies subscribers when match scores change. Perfect for testing real-time sports apps.

WEBHOOK CONFIG
Name: Score Update Notification
Method: POST
URL: https://your-app.com/webhooks/score
Bound to: PUT /api/matches/:matchId/score
USE CASES
  • â€ĸ Push notifications to mobile apps
  • â€ĸ Update live scoreboards
  • â€ĸ Trigger betting system updates
  • â€ĸ Feed social media bots
REQUEST BODY
{
  "type": "score_update",
  "matchId": "{{request.path.matchId}}",
  "homeTeam": "{{request.body.homeTeam}}",
  "awayTeam": "{{request.body.awayTeam}}",
  "homeScore": {{request.body.homeScore}},
  "awayScore": {{request.body.awayScore}},
  "minute": {{request.body.minute}},
  "eventType": "{{request.body.eventType}}",
  "timestamp": "{{request.timestamp}}"
}

Stock Market: Price Alerts

Simulate a trading platform that sends alerts when stock prices hit certain thresholds.

WEBHOOK CONFIG
Name: Stock Price Alert
Method: POST
URL: https://trading-app.com/alerts
Auth: API Key (X-Trading-Key)
Bound to: POST /api/stocks/:symbol/price
USE CASES
  • â€ĸ Price threshold alerts
  • â€ĸ Portfolio rebalancing triggers
  • â€ĸ Market volatility notifications
  • â€ĸ Automated trading signals
REQUEST BODY
{
  "alert": "price_threshold",
  "symbol": "{{request.path.symbol}}",
  "currentPrice": {{request.body.price}},
  "change": {{request.body.changePercent}},
  "volume": {{request.body.volume}},
  "timestamp": "{{request.timestamp}}",
  "alertId": "{{random.uuid}}"
}

AI/ML: Model Inference Callbacks

Simulate async AI/ML processing where results are delivered via callback after model inference completes.

WEBHOOK CONFIG
Name: ML Inference Callback
Method: POST
URL: https://app.com/ml/callback
Delay: 2000ms (simulate processing)
Auth: Bearer Token
Bound to: POST /api/ml/jobs/:jobId
USE CASES
  • â€ĸ Image classification results
  • â€ĸ NLP processing completion
  • â€ĸ Recommendation engine outputs
  • â€ĸ Batch prediction results
REQUEST BODY
{
  "jobId": "{{request.path.jobId}}",
  "status": "completed",
  "model": "{{request.body.model}}",
  "result": {
    "prediction": {{request.body.prediction}},
    "confidence": {{request.body.confidence}},
    "processingTime": {{request.body.processingTimeMs}}
  },
  "callbackId": "{{random.uuid}}",
  "completedAt": "{{request.timestamp}}"
}

Payment Processing: Transaction Callbacks

Simulate payment gateway callbacks (like Stripe, PayPal) that notify your app when transactions complete.

WEBHOOK CONFIG
Name: Payment Completed
Method: POST
URL: http://localhost:3000/webhooks/payment
Delay: 1500ms
Retry: 3 attempts, 2000ms delay
Bound to: POST /api/payments/charge
USE CASES
  • â€ĸ Order fulfillment triggers
  • â€ĸ Subscription activation
  • â€ĸ Receipt generation
  • â€ĸ Inventory updates
REQUEST BODY
{
  "event": "payment.completed",
  "transactionId": "{{random.uuid}}",
  "orderId": "{{request.body.orderId}}",
  "amount": {{request.body.amount}},
  "currency": "{{request.body.currency}}",
  "paymentMethod": "{{request.body.paymentMethod}}",
  "status": "success",
  "processedAt": "{{request.timestamp}}",
  "metadata": {
    "customerId": "{{request.body.customerId}}",
    "description": "{{request.body.description}}"
  }
}

E-commerce: Order Shipping Notifications

Simulate shipping carrier webhooks that notify customers when orders are shipped with tracking info.

WEBHOOK CONFIG
Name: Order Shipped Notification
Method: POST
URL: https://shop.com/webhooks/shipping
Bound to: PUT /api/orders/:orderId/ship
USE CASES
  • â€ĸ Customer email notifications
  • â€ĸ SMS tracking updates
  • â€ĸ Order status page updates
  • â€ĸ Delivery estimate calculations
REQUEST BODY
{
  "event": "order.shipped",
  "orderId": "{{request.path.orderId}}",
  "trackingNumber": "{{random.uuid}}",
  "carrier": "{{request.body.carrier}}",
  "estimatedDelivery": "{{request.body.estimatedDelivery}}",
  "items": {{request.body.items}},
  "shippingAddress": {{request.body.shippingAddress}},
  "notifiedAt": "{{request.timestamp}}"
}

IoT: Sensor Alerts

Simulate IoT device webhooks that alert when sensor readings exceed thresholds.

WEBHOOK CONFIG
Name: Sensor Alert
Method: POST
URL: https://iot-platform.com/alerts
Auth: API Key
Bound to: POST /api/devices/:deviceId/reading
USE CASES
  • â€ĸ Temperature threshold alerts
  • â€ĸ Motion detection notifications
  • â€ĸ Equipment malfunction warnings
  • â€ĸ Environmental monitoring
REQUEST BODY
{
  "deviceId": "{{request.path.deviceId}}",
  "sensorType": "{{request.body.sensorType}}",
  "reading": {
    "value": {{request.body.value}},
    "unit": "{{request.body.unit}}",
    "threshold": {{request.body.threshold}}
  },
  "alertLevel": "{{request.body.alertLevel}}",
  "location": {
    "lat": {{request.body.latitude}},
    "lng": {{request.body.longitude}}
  },
  "timestamp": "{{request.timestamp}}"
}

Slack: Team Notifications

Send formatted messages to Slack channels when important events occur.

WEBHOOK CONFIG
Name: Slack Order Alert
Method: POST
URL: https://hooks.slack.com/services/T.../B.../xxx
Headers: Content-Type: application/json
Bound to: POST /api/orders/:orderId
USE CASES
  • â€ĸ New order notifications
  • â€ĸ Error alerts to dev channels
  • â€ĸ Deployment status updates
  • â€ĸ Customer support tickets
REQUEST BODY (Slack Block Kit)
{
  "text": "New Order Received!",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "*Order #{{request.path.orderId}}*\nCustomer: {{request.body.customer.name}}\nTotal: ${{request.body.total}}"
      }
    }
  ]
}

Discord: Game/Community Updates

Send rich embed messages to Discord channels for community updates.

WEBHOOK CONFIG
Name: Discord Match Update
Method: POST
URL: https://discord.com/api/webhooks/...
Bound to: PUT /api/matches/:matchId
USE CASES
  • â€ĸ Game server status updates
  • â€ĸ Tournament bracket changes
  • â€ĸ Community event reminders
  • â€ĸ Leaderboard updates
REQUEST BODY (Discord Embed)
{
  "content": "Match Update!",
  "embeds": [{
    "title": "{{request.body.homeTeam}} vs {{request.body.awayTeam}}",
    "description": "Score: {{request.body.homeScore}} - {{request.body.awayScore}}",
    "color": 5814783,
    "fields": [
      {"name": "Minute", "value": "{{request.body.minute}}'", "inline": true},
      {"name": "Event", "value": "{{request.body.eventType}}", "inline": true}
    ],
    "timestamp": "{{request.timestamp}}"
  }]
}

Microservices: Inter-Service Communication

Simulate event-driven architecture where services communicate via webhooks.

WEBHOOK CONFIG
Name: Inventory Reserve
Method: POST
URL: http://inventory-service:8080/reserve
Delay: 100ms
Bound to: POST /api/orders/:orderId
USE CASES
  • â€ĸ Order → Inventory sync
  • â€ĸ User → Notification service
  • â€ĸ Payment → Fulfillment trigger
  • â€ĸ Analytics event streaming
REQUEST BODY
{
  "eventType": "inventory.reserve",
  "correlationId": "{{request.header.X-Correlation-Id}}",
  "orderId": "{{request.path.orderId}}",
  "items": {{request.body.items}},
  "warehouseId": "{{request.body.warehouseId}}",
  "priority": "{{request.body.priority}}",
  "requestedAt": "{{request.timestamp}}"
}

Audit Logging: Compliance & Security

Send all API activity to an audit service for compliance and security monitoring.

WEBHOOK CONFIG
Name: Audit Logger
Method: POST
URL: https://audit.internal/logs
Auth: API Key (X-Audit-Key)
Retry: 5 attempts (critical data)
Bound to: Multiple sensitive endpoints
USE CASES
  • â€ĸ GDPR/HIPAA compliance logging
  • â€ĸ Security incident tracking
  • â€ĸ User activity monitoring
  • â€ĸ Data change history
REQUEST BODY
{
  "eventId": "{{random.uuid}}",
  "timestamp": "{{request.timestamp}}",
  "action": "{{request.body.action}}",
  "resource": "{{request.body.resource}}",
  "resourceId": "{{request.path.id}}",
  "userId": "{{request.header.X-User-Id}}",
  "ipAddress": "{{request.header.X-Forwarded-For}}",
  "userAgent": "{{request.header.User-Agent}}",
  "changes": {{request.body.changes}}
}

Social Media: Activity Notifications

Simulate social platform webhooks for likes, follows, comments, and other interactions.

WEBHOOK CONFIG
Name: New Follower Alert
Method: POST
URL: https://app.com/webhooks/social
Bound to: POST /api/users/:userId/follow
USE CASES
  • â€ĸ Push notifications for new followers
  • â€ĸ Like/comment activity feeds
  • â€ĸ Milestone achievement alerts
  • â€ĸ Creator dashboard updates
REQUEST BODY
{
  "event": "new_follower",
  "userId": "{{request.path.userId}}",
  "follower": {
    "id": "{{request.body.followerId}}",
    "username": "{{request.body.followerUsername}}",
    "displayName": "{{request.body.followerDisplayName}}"
  },
  "totalFollowers": {{request.body.totalFollowers}},
  "timestamp": "{{request.timestamp}}",
  "notificationId": "{{random.uuid}}"
}

Webhook History & Monitoring

Every webhook execution is logged and visible in the Response tab of your webhook. Monitor, debug, and verify that your webhooks are working correctly in real-time.

What's captured in history:

✓ Request details (method, URL, headers, body sent)
✓ Response details (status code, headers, body received)
✓ Timing (duration in milliseconds)
✓ Trigger info (which endpoint triggered it)
✓ Retry attempts (attempt number and max attempts)
✓ Status (success/failure with error messages)

Real-time updates: Webhook history updates instantly via Server-Sent Events (SSE). Results appear automatically as webhooks execute - no refresh needed!

Testing Webhooks

Mocklantis provides a "Try" button to manually test webhooks without triggering them from an endpoint.

📍 How to Test:

  1. Select your webhook in the sidebar
  2. Click the "Try" button in the header
  3. The webhook executes immediately
  4. Check the Response tab for results

âš ī¸ Note:

When testing manually, template variables like {{request.body.field}} won't have real values since there's no triggering request. Use {{random.uuid}} or hardcoded test values for manual testing.

Retry Logic

Configure automatic retries for webhooks that fail due to network issues or temporary service outages.

How retries work:

Attempt 1: Failed (timeout)
    ↓ Wait retryDelay (1000ms)
Attempt 2: Failed (500 error)
    ↓ Wait retryDelay (1000ms)
Attempt 3: Success! (200 OK)

✅ Success Criteria

HTTP status 200-299 is considered successful. Retries stop immediately on success.

❌ Failure Criteria

Non-2xx status codes, timeouts, or connection errors trigger retries until max attempts reached.

Troubleshooting

Webhook not firing?

  • Check if the webhook is bound to the endpoint you're calling
  • Verify the mock server is running
  • Check the webhook URL is valid (http:// or https://)
  • Look for any validation errors in the webhook configuration

Getting timeout errors?

  • Increase the timeout value in Settings tab
  • Check if the target URL is reachable from your machine
  • Verify no firewall or VPN is blocking the connection
  • Try the URL in a browser or with curl first

SSL certificate errors?

  • Enable "Skip SSL Verification" in Settings tab for self-signed certs
  • This is common in development/staging environments
  • Don't use this option when connecting to production services

Template variables not working?

  • Check the syntax: {{request.path.id}} not {{path.id}}
  • Include the request. prefix for request data
  • Ensure the triggering request has the expected data
  • For body JSONPath, verify the path exists in the request body
  • Check for typos in variable names (case-sensitive for body paths)

History not showing results?

  • Select the webhook in the sidebar to see its history
  • History is stored per-webhook, not globally
  • Results update in real-time via SSE - check your network connection
  • History persists during the session but clears when you close Mocklantis

Authentication not working?

  • For Basic Auth, ensure username and password are both provided
  • For Bearer Token, check the token doesn't have extra whitespace
  • For API Key, verify the header name matches what the service expects
  • Check the Response tab to see what headers were actually sent

Summary

Webhooks are perfect for:

  • ✓ Testing notification systems (Slack, Discord, Email)
  • ✓ Simulating payment gateway callbacks
  • ✓ Mocking inter-service communication
  • ✓ Testing async/event-driven workflows
  • ✓ Audit logging simulation
  • ✓ IoT device event handling
  • ✓ AI/ML job completion callbacks
  • ✓ Real-time score/data updates

Key features:

  • ✓ Fire-and-forget execution
  • ✓ Template variable support
  • ✓ Multiple authentication methods
  • ✓ Configurable retry logic
  • ✓ Real-time history monitoring
  • ✓ Delay simulation for realism
  • ✓ SSL verification control
  • ✓ Multi-endpoint binding

Tips & Best Practices

💡

Use descriptive names so you know what webhooks do at a glance. Example: "Slack Notification - Order Created" instead of "Webhook 1"

💡

Set appropriate timeouts - 30 seconds is usually plenty for most external services

💡

Add delays (100-2000ms) to simulate real-world latency from payment processors and external services

💡

Configure retries (3-5) for critical webhooks like audit logging that must succeed

âš ī¸

Double-check webhook URLs before testing - don't accidentally send test data to production systems!

âš ī¸

Credentials are stored locally - don't commit sensitive data to version control

đŸŽ¯

Use the "Try" button to test webhooks without triggering from an endpoint

đŸŽ¯

Check the Response tab to debug template variable issues and see what was actually sent

WebSocket Endpoints

Simulate and test real-time WebSocket connections with Mocklantis.

Quick Start

Creating a WebSocket endpoint takes just 3 steps:

  1. Set the path: /ws/chat
  2. Choose a mode: Conversational, Streaming, or Triggered Streaming
  3. Configure messages: Add patterns and responses

Path Configuration

Define the access path for your WebSocket endpoint. The path must always start with /.

Example Paths:

✓/ws/chat- Simple chat WebSocket
✓/api/v1/notifications- Notification stream
✓/live/stock-prices- Live stock data

💡 Tip: You can change the path while the server is running, active connections are preserved!

Mode Selection

Mocklantis offers 3 different WebSocket modes. Each mode is designed for different use cases:

đŸ’Ŧ

Conversational Mode

Responds to each incoming message based on specific patterns.

When to use: Chat applications, command-based systems, Q&A bots

Example: User sends "hello" → Responds with "Hi there!"

📡

Streaming Mode

Automatically sends periodic messages when a connection is established.

When to use: Live data feeds, sensor data, real-time analytics

Example: Current stock prices every 1 second

đŸŽ¯

Triggered Streaming Mode

Starts a stream when a specific message is received, sends an initial response, then sends periodic messages.

When to use: On-demand data streams, progressive loading, long-running operations

Example: "start" message → Initial response → Progress updates every 2s

Connection Example

Once your server is running, you can connect to your WebSocket endpoint like this:

JavaScript:

const ws = new WebSocket('ws://localhost:5678/ws/chat');

ws.onopen = () => {
    console.log('Connected!');
    ws.send('Hello server!');
};

ws.onmessage = (event) => {
    console.log('Received:', event.data);
};

Python:

import websocket

ws = websocket.create_connection('ws://localhost:5678/ws/chat')
ws.send('Hello server!')
result = ws.recv()
print(f'Received: {result}')

Next Steps

Explore Modes in Detail

Learn the detailed features and examples of each mode

Lifecycle Events

Automatic message sending on connection

Advanced Options

Advanced configurations and customizations

Tips & Best Practices

✅

Edit while server is running: When you change endpoint configuration, there's no need to restart the server, changes apply instantly!

💡

Test your patterns: In Conversational and Triggered Streaming modes, test your patterns with simple messages.

⚡

Performance: Don't set streaming interval too low (minimum 100ms recommended), otherwise clients may be affected by message load.

đŸ’Ŧ Conversational Mode

Intelligently respond to every incoming message based on patterns. Perfect for chat bots, command systems, and interactive applications!

How Does It Work?

In Conversational Mode, when a client sends a message, Mocklantis checks the pattern list from top to bottom. It sends the response of the first matching pattern.

Workflow:
1Client sends a message
2Mocklantis checks patterns in order
3Sends the response of the first matching pattern
4If no match is found, stays silent

Pattern Types

Mocklantis offers 4 powerful pattern matching types. Each is optimized for different scenarios:

đŸŽ¯
EXACT Match - Exact Matching

The incoming message must be exactly the same as the pattern. Case-sensitive and whitespace matters.

Pattern:

hello

Results:

✓hello→ Matches
✗Hello→ No match (uppercase)
✗hello world→ No match (extra words)

💡 When to use:

  • Command-based systems: /help, /start
  • Fixed API commands: PING, STATUS
  • Specific event names: user:login

Real-Life Example:

Pattern:

/balance

Response:

{
  "balance": 1250.50,
  "currency": "USD"
}
🔍
CONTAINS Match - Contains

Matches if the incoming message contains the pattern. The most flexible matching type.

Pattern:

error

Results:

✓error→ Matches
✓connection error→ Matches
✓There was an error in processing→ Matches
✗Error→ No match (case-sensitive)

💡 When to use:

  • Keyword-based responses: messages containing "help"
  • Natural language processing: messages containing "hello", "hi"
  • Error catching: messages containing "error", "failed"

Real-Life Example - Chat Bot:

Pattern:

price

Response:

Our premium plan is $29/month. Type "subscribe" to get started!

This pattern catches these messages:

  • "What's the price?"
  • "price info please"
  • "Tell me about pricing"
⚡
REGEX Match - Regular Expression

Use regex for advanced pattern matching. The most powerful and flexible option.

Example 1: Email Validation

Pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
✗invalid-email

Example 2: Phone Number

Pattern: ^\d{10}$
✓5551234567
✗555-123-4567

Example 3: Command Parameters

Pattern: /send (.*) to (.*)
✓/send money to john
✓/send file to team

💡 When to use:

  • Format validation: email, phone, credit card
  • Parameterized commands: /order [product] qty:[number]
  • Complex patterns: code snippets, URLs
  • Case-insensitive match: (?i)hello

Real-Life Example - Order System:

Pattern:

^order #(\d+)$

Response:

{
  "orderId": "12345",
  "status": "shipped",
  "trackingNumber": "ABC123XYZ"
}
Matches: order #12345, order #999

âš ī¸ Warning: Regex syntax errors will prevent the pattern from working. Test it!

đŸ“Ļ
JSON_PATH Match - JSON Path Queries

Check specific fields in JSON messages. Ideal for modern APIs!

Example 1: Root Level Field

Pattern: $.type
Incoming message:
{
  "type": "message",
  "content": "Hello"
}
✓Matches! (type field exists)

Example 2: Nested Object

Pattern: $.user.profile.role
Incoming message:
{
  "user": {
    "profile": {
      "role": "admin"
    }
  }
}
✓Matches! ($.user.profile.role exists)

Example 3: Array Element

Pattern: $.users[0].name
Incoming message:
{
  "users": [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25}
  ]
}
✓Matches! (First user's name exists)

Example 4: Nested in Array

Pattern: $.data.items[1].status
Incoming message:
{
  "data": {
    "items": [
      {"id": 101, "status": "active"},
      {"id": 102, "status": "pending"}
    ]
  }
}
✓Matches! (Second item's status exists)

💡 When to use:

  • Event type routing: respond based on event type via $.event
  • Auth checks: check if $.auth.token exists
  • Nested data: $.order.payment.method
  • Array operations: $.cart.items[0].id

Real-Life Example - Event Router:

Pattern 1: User Login Event

$.event

Message: {"event":"login","user":"john"}

Response:

{
  "status": "success",
  "message": "Welcome back!",
  "sessionId": "abc123"
}

💡 Pro Tip: JSON Path only checks for field existence, not its value. Use REGEX for value checking.

Response Templating

Use {{request.message}} to reference the incoming message in your response. For JSON messages, you can access specific fields using dot notation.

🔄
Echo & Transform Messages

Example 1: Full Message Echo

Incoming:

{"action":"login","user":"john"}

Response Template:

{
  "type": "echo",
  "received": {{request.message}}
}

Actual Response:

{
  "type": "echo",
  "received": {"action":"login","user":"john"}
}

Example 2: Extract Specific Fields

Incoming:

{"action":"subscribe","channel":"news","userId":"123"}

Response Template:

{
  "status": "subscribed",
  "channel": "{{request.message.channel}}",
  "user": "{{request.message.userId}}"
}

Actual Response:

{
  "status": "subscribed",
  "channel": "news",
  "user": "123"
}

Example 3: Nested JSON Access

Incoming:

{
  "event": "order",
  "data": { "product": "Widget", "quantity": 5 }
}

Response Template:

{
  "confirmed": true,
  "product": "{{request.message.data.product}}",
  "qty": "{{request.message.data.quantity}}"
}

Actual Response:

{
  "confirmed": true,
  "product": "Widget",
  "qty": "5"
}

💡 Available Variables:

  • {{request.message}} - Full incoming message
  • {{request.message.field}} - Specific JSON field
  • {{request.message.nested.field}} - Nested field access
  • {{request.timestamp}} - Current ISO timestamp
  • {{random.uuid}} - Random UUID (and other random variables)

Response Configuration

Response Delay

You can add an optional delay (in milliseconds) for each pattern.

Delay: 0ms

→ Instant response (default)

Delay: 1000ms

→ Response after 1 second

Delay: 3000ms

→ Response after 3 seconds (slow network simulation)

💡 Use Cases:

  • Network latency simulation
  • Slow server testing (timeout tests)
  • Progressive loading UX testing
  • Realistic delay for "Thinking..." animations
Response Format

Response can be plain text or JSON. Mocklantis automatically determines content-type.

Plain Text:

Hello! How can I help you?

JSON:

{
  "message": "Hello!",
  "timestamp": 1234567890,
  "userId": "user123"
}

Pattern Priority

Patterns are checked from top to bottom. The first matching pattern wins!

âš ī¸ Important: Ordering Strategy

  • Put specific patterns at the top
  • Put general patterns at the bottom (as fallback)
  • CONTAINS type is the most general, use carefully

Bad Example ❌:

1.
help(CONTAINS)
2.
/help balance(EXACT)

→ Pattern 1 catches EVERY message containing "help", Pattern 2 never gets reached!

Good Example ✅:

1.
/help balance(EXACT)
2.
/help order(EXACT)
3.
help(CONTAINS - fallback)

→ Specific commands are checked first, if no match, general help message is sent.

Complete Example: Support Bot

A real customer support bot scenario. Uses all pattern types:

Pattern #1 - GreetingCONTAINS

Pattern: hello

Response: Hi! I'm your support assistant. How can I help you today?

Delay: 0ms

Pattern #2 - Order StatusREGEX

Pattern: ^order #(\d+)$

Response:

{
  "orderId": "12345",
  "status": "shipped",
  "estimatedDelivery": "2024-01-20"
}

Delay: 500ms

Pattern #3 - Account BalanceEXACT

Pattern: /balance

Response:

{
  "balance": 1250.50,
  "currency": "USD",
  "lastUpdated": "2024-01-15T10:30:00Z"
}

Delay: 800ms

Pattern #4 - Event RoutingJSON_PATH

Pattern: $.action

Message: {"action":"subscribe","plan":"premium"}

Response:

{
  "status": "subscribed",
  "plan": "premium",
  "nextBillingDate": "2024-02-15"
}

Delay: 1000ms

Pattern #5 - FallbackCONTAINS

Pattern: . (any character)

Response: I didn't understand that. Type "help" for available commands.

Delay: 0ms

Best Practices

✅

Put specific patterns at the top

Check special cases first, then general cases.

✅

Use descriptive names for each pattern

Give names that describe the pattern's purpose: "Login Handler", "Order Status Query"

✅

Use realistic delays

Simulate your production environment's response times.

✅

Add a fallback pattern

Add a general CONTAINS pattern at the end to respond to unexpected messages.

❌

Don't use CONTAINS as the first pattern

Very general patterns can prevent other patterns from working.

❌

Don't use regex for simple matches

If EXACT or CONTAINS is sufficient, don't use regex for performance reasons.

📡 Streaming Mode

Automatically send periodic messages when a connection is established. Perfect for real-time data feeds, sensor data, and live updates!

How Does It Work?

In Streaming Mode, as soon as the client connects to the WebSocket, Mocklantis automatically starts sending periodic messages. The stream continues even if the client doesn't send any messages.

Workflow:
1Client connects to WebSocket
2Mocklantis automatically starts the stream
3Messages are sent sequentially at the specified interval
4When the message list ends, it loops back to the beginning (circular)
5Continues until the client disconnects

Configuration

âąī¸Streaming Interval

Wait time between messages (in milliseconds). This interval remains constant.

100ms→ Very fast (10 messages per second)
1000ms→ Normal (1 message per second)
5000ms→ Slow (1 message per 5 seconds)

âš ī¸ Performance Note: Don't set the interval too low (minimum 100ms recommended). Very fast streams can overwhelm the client's processing capacity.

💡 Tip: You can change the interval while the server is running, and the change takes effect immediately!

📝Stream Messages

List of messages to be sent. Messages are sent sequentially and loop back to the beginning when the list ends.

Message Formats:

Plain Text:

Stock price: $150.25

JSON:

{
  "symbol": "AAPL",
  "price": 150.25,
  "timestamp": 1234567890
}

XML:

<stock>
  <symbol>AAPL</symbol>
  <price>150.25</price>
</stock>

💡 Circular Streaming: Messages are sent in sequence and automatically loop back to the beginning when the list ends. This creates an infinite loop!

Use Cases

Streaming Mode is perfect for many real-time applications:

📈
Stock / Crypto Prices

Simulate live price updates.

Configuration:

Interval: 1000ms (1 second)

Messages: 10-15 different price values

Example Message:

{
  "symbol": "BTC",
  "price": 42350.75,
  "change": "+2.5%",
  "volume": 1250000000
}
đŸŒĄī¸
IoT Sensor Data

Simulate sensor data such as temperature, humidity, and pressure.

Configuration:

Interval: 2000ms (2 seconds)

Messages: Different sensor readings

Example Message:

{
  "sensorId": "TEMP-001",
  "temperature": 23.5,
  "humidity": 65,
  "timestamp": "2024-01-15T10:30:00Z"
}
âšŊ
Live Sports Scores

Match scores, statistics, and updates.

Configuration:

Interval: 3000ms (3 seconds)

Messages: Different match states

Example Messages:

Message 1: {"score": "1-0", "minute": "15"}
Message 2: {"score": "1-0", "minute": "30"}
Message 3: {"score": "2-0", "minute": "42"}
Message 4: {"score": "2-1", "minute": "68"}
📊
System Monitoring

System metrics such as CPU, RAM, and disk usage.

Configuration:

Interval: 5000ms (5 seconds)

Messages: Different metric values

Example Message:

{
  "cpu": 45.2,
  "memory": 62.8,
  "disk": 78.5,
  "network": 125.3
}
đŸ’Ŧ
Chat Activity Feed

Live chat messages and user activities.

Configuration:

Interval: 4000ms (4 seconds)

Messages: Different user messages

Example Messages:

Message 1: {"user": "Alice", "text": "Hello!"}
Message 2: {"user": "Bob", "text": "How are you?"}
Message 3: {"user": "Charlie", "text": "Great!"}
âŗ
Progress Updates

Progress status of long-running operations.

Configuration:

Interval: 2000ms (2 seconds)

Messages: Progress values from 0% to 100%

Example Messages:

Message 1: {"progress": 10, "status": "Processing..."}
Message 2: {"progress": 25, "status": "Processing..."}
Message 3: {"progress": 50, "status": "Half way..."}
Message 4: {"progress": 75, "status": "Almost done..."}
Message 5: {"progress": 100, "status": "Complete!"}

Complete Example: Crypto Price Tracker

A real cryptocurrency exchange simulation. Continuously changing prices, volume, and percentage changes:

Configuration

Path: /live/crypto

Mode: Streaming

Interval: 1500ms (1.5 seconds)

Stream Messages (10 messages):

Message #1:

{
  "symbol": "BTC/USD",
  "price": 42150.25,
  "change": "+1.2%",
  "volume": 1250000000,
  "timestamp": 1767225600000
}

Message #2:

{
  "symbol": "BTC/USD",
  "price": 42180.5,
  "change": "+1.3%",
  "volume": 1255000000,
  "timestamp": 1767225601500
}

Message #3:

{
  "symbol": "BTC/USD",
  "price": 42165.75,
  "change": "+1.2%",
  "volume": 1260000000,
  "timestamp": 1767225603000
}

Message #4:

{
  "symbol": "BTC/USD",
  "price": 42200,
  "change": "+1.4%",
  "volume": 1270000000,
  "timestamp": 1767225604500
}

Message #5:

{
  "symbol": "BTC/USD",
  "price": 42175.25,
  "change": "+1.3%",
  "volume": 1265000000,
  "timestamp": 1767225606000
}

Message #6:

{
  "symbol": "BTC/USD",
  "price": 42190.5,
  "change": "+1.3%",
  "volume": 1275000000,
  "timestamp": 1767225607500
}

Message #7:

{
  "symbol": "BTC/USD",
  "price": 42210.75,
  "change": "+1.4%",
  "volume": 1280000000,
  "timestamp": 1767225609000
}

Message #8:

{
  "symbol": "BTC/USD",
  "price": 42195,
  "change": "+1.4%",
  "volume": 1278000000,
  "timestamp": 1767225610500
}

Message #9:

{
  "symbol": "BTC/USD",
  "price": 42220.25,
  "change": "+1.5%",
  "volume": 1285000000,
  "timestamp": 1767225612000
}

Message #10:

{
  "symbol": "BTC/USD",
  "price": 42205.5,
  "change": "+1.4%",
  "volume": 1282000000,
  "timestamp": 1767225613500
}

💡 How It Works:

  1. Client connects
  2. A message is sent every 1.5 seconds
  3. After 10 messages, it loops back to the beginning (Message #1)
  4. Continues as an infinite loop
  5. Runs until the client disconnects
Example Client Code:
const ws = new WebSocket('ws://localhost:5678/live/crypto');

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log(`BTC Price: $${data.price} (${data.change})`);

    // Update UI
    updatePriceChart(data);
};

// Output:
// BTC Price: $42150.25 (+1.2%)
// BTC Price: $42180.50 (+1.3%)
// BTC Price: $42165.75 (+1.2%)
// ...

Best Practices

✅ Use realistic intervals

Simulate the update frequency of your production environment.

✅ Add variation

Add 10-20 different messages to provide realistic data diversity.

✅ Include timestamps

Add timestamps to messages so clients can check data freshness.

✅ Use linear values for progress simulation

Use incrementing values like 0-100 to test loading/progress UIs.

❌ Don't use very low intervals

Intervals below 100ms can overload the client and cause performance issues.

❌ Don't add too few messages

A loop with 1-2 messages repeats too quickly and isn't realistic. Add at least 5-10 messages.

Dynamic Updates

⚡Live Configuration Changes

One of Mocklantis's most powerful features: You can change everything while the server is running!

✓Change the interval → Takes effect immediately
✓Add/delete messages → Active in the next cycle
✓Change message content → Updates instantly
✓Active connections are preserved → Clients don't disconnect

Example Scenario:

  1. Server started, 3 clients connected, interval: 2000ms
  2. You changed the interval to 1000ms
  3. Clients stayed connected, new interval applied immediately
  4. You added 2 new messages
  5. New messages were included in the stream in the next cycle

Tips

💡 Testing Strategy: Start with a large interval (5000ms) and verify the messages. Then gradually reduce the interval to achieve a realistic speed.

💡 Data Variety: Instead of sending the same message repeatedly, create different versions with small variations (price, timestamp, etc.).

💡 Client Disconnection Test: Test your reconnection logic by disconnecting and reconnecting the client while the stream is active.

💡 Multiple Clients: Connect multiple clients to verify that each receives an independent stream with their own timer.

đŸŽ¯ Triggered Streaming Mode

Start a stream based on client messages, send an initial response, then send periodic messages and stop automatically. Ideal for long-running operations, progressive loading, and on-demand data streams!

How Does It Work?

Triggered Streaming Mode is a combination of Conversational and Streaming Modes. The client sends a "trigger" message, Mocklantis matches it against patterns, immediately sends the initial response, then begins sending stream messages at the specified interval and stops after the specified duration/count.

Workflow:
1Client sends trigger message (e.g., "start download")
2Mocklantis checks patterns (EXACT, CONTAINS, REGEX, JSON_PATH)
3If matching pattern found, initial response is sent immediately
4Stream starts, stream messages are sent at specified interval
5Stream stops when stopAfter duration expires OR stopCount is reached
6If client sends new trigger message, cycle restarts

Configuration

In Triggered Streaming, you configure each trigger pattern separately:

đŸŽ¯Incoming Pattern (Optional)

The message pattern that will trigger the stream. Supports 4 types like Conversational Mode: EXACT, CONTAINS, REGEX, JSON_PATH. If left empty, EVERY message triggers.

Examples:

start(EXACT) - Only "start" triggers
download(CONTAINS) - Messages containing "download"
^process (\d+)$(REGEX) - Like "process 123"
$.action(JSON_PATH) - JSON with action field
(empty)- EVERY message triggers

💡 Pro Tip: With an empty pattern, you get "any message triggers stream" behavior. Perfect for using the first message as a trigger to start streaming!

⚡Initial Response

The first response sent immediately when a trigger message is received. This message comes before the stream and typically means "processing started."

Example 1: Plain Text

Processing started...

Example 2: JSON

{
  "status": "started",
  "jobId": "job-123",
  "message": "Download initiated"
}

âš ī¸ Important: Initial response is separate from stream messages. This is sent first, then after the interval the first stream message arrives.

📨Stream Messages

Messages sent periodically after the initial response. The list is sent in order and loops back to the beginning (circular).

Example: Progress Updates

Message 1: {"progress": 10}
Message 2: {"progress": 25}
Message 3: {"progress": 50}
Message 4: {"progress": 75}
Message 5: {"progress": 100, "status": "complete"}

💡 Tip: For progress simulation, use linear values (0, 20, 40, 60, 80, 100). For log streaming, add different log lines!

âąī¸Interval

The wait time between stream messages (in milliseconds).

500ms→ Fast updates (2 messages per second)
1000ms→ Normal speed (1 message per second)
2000ms→ Slow updates (1 message per 2 seconds)
🛑Stop Conditions

When will the stream stop? There are two conditions - whichever occurs first stops the stream:

stopAfter (Required) - Time-based

Maximum duration in milliseconds after stream starts (Max: 600000ms = 10 minutes)

10000ms→ Stop after 10 seconds
30000ms→ Stop after 30 seconds
60000ms→ Stop after 1 minute

stopCount (Optional) - Count-based

Stop after how many stream messages? (Max: 50 messages, can be left empty)

5→ Stop after 5 messages
10→ Stop after 10 messages
(empty)→ Only use stopAfter

âš ī¸ Critical: Stream stopping logic: stopAfter OR stopCount - whichever comes first! If both are set, the first to occur wins.

Example Scenario:

  • â€ĸ Interval: 1000ms (1 message per second)
  • â€ĸ stopAfter: 10000ms (10 seconds)
  • â€ĸ stopCount: 5
  • â€ĸ Result: Stops after 5th message (5 seconds), because stopCount was reached first

Response Templating

Use {{request.message}} to reference the trigger message in your responses. Works in both Initial Response and Stream Messages!

🔄
Echo Trigger Data in Responses

Example: File Processing with Trigger Data

Trigger Message:

{"action":"process","fileId":"abc123","format":"mp4"}

Initial Response Template:

{
  "status": "started",
  "fileId": "{{request.message.fileId}}",
  "format": "{{request.message.format}}",
  "jobId": "{{random.uuid}}"
}

Actual Initial Response:

{
  "status": "started",
  "fileId": "abc123",
  "format": "mp4",
  "jobId": "f7e8d9c0-1234-5678-abcd-ef0123456789"
}

Stream Messages with Trigger Data:

Stream Message Template:

{
  "fileId": "{{request.message.fileId}}",
  "progress": {{random.number(1,100)}},
  "timestamp": "{{request.timestamp}}"
}

Actual Stream Messages:

{"fileId": "abc123", "progress": 23, "timestamp": "2024-..."}
{"fileId": "abc123", "progress": 67, "timestamp": "2024-..."}
{"fileId": "abc123", "progress": 91, "timestamp": "2024-..."}

💡 Available Variables:

  • {{request.message}} - Full trigger message
  • {{request.message.field}} - Specific JSON field
  • {{request.message.nested.field}} - Nested field access
  • {{request.timestamp}} - Current ISO timestamp
  • {{random.uuid}} - Random UUID (and other random variables)

âš ī¸ Note: The trigger message is captured when the stream starts. All stream messages reference the same trigger message throughout the stream.

Use Cases

Triggered Streaming Mode is ideal for the most complex and realistic scenarios:

📤
File Upload Progress

Send progress updates while a file is being uploaded.

Configuration:

Pattern: upload (CONTAINS)

Initial Response: {"status":"uploading","fileId":"f123"}

Interval: 500ms

stopAfter: 10000ms (10 seconds)

stopCount: 20

Stream Messages:

{"progress": 5, "bytesUploaded": 512000}
{"progress": 10, "bytesUploaded": 1024000}
{"progress": 20, "bytesUploaded": 2048000}
...
{"progress": 100, "status": "complete"}
đŸŽŦ
Video Processing

Progress and log messages during video encoding/decoding.

Configuration:

Pattern: $.action (JSON_PATH)

Trigger: {"action":"encode","video":"vid.mp4"}

Initial Response: {"status":"encoding","jobId":"enc-456"}

Interval: 2000ms

stopAfter: 60000ms (1 minute)

Stream Messages:

{"stage": "analyzing", "progress": 10}
{"stage": "encoding", "progress": 30}
{"stage": "encoding", "progress": 60}
{"stage": "finalizing", "progress": 90}
{"stage": "complete", "progress": 100, "url": "..."}
🤖
AI Text Generation

ChatGPT-style streaming response - delivered word by word.

Configuration:

Pattern: generate (CONTAINS)

Initial Response: {"thinking": true}

Interval: 300ms

stopAfter: 15000ms

stopCount: 30

Stream Messages (word by word):

{"token": "The"}
{"token": "quick"}
{"token": "brown"}
{"token": "fox"}
{"token": "jumps"}
...
{"done": true}
🔨
Build / Deploy Process

CI/CD pipeline logs, build progress, deployment stages.

Configuration:

Pattern: ^deploy (.*)$ (REGEX)

Trigger: deploy production

Initial Response: Deployment started...

Interval: 1500ms

stopAfter: 45000ms

Stream Messages:

[LOG] Building Docker image...
[LOG] Running tests...
[LOG] Tests passed ✓
[LOG] Pushing to registry...
[LOG] Deploying to k8s...
[LOG] Deployment complete! ✓
💾
Large Data Export

Large data export process, chunk-by-chunk progress.

Configuration:

Pattern: (empty) - EVERY message triggers

Initial Response: {"exportId":"exp-789","status":"started"}

Interval: 1000ms

stopAfter: 30000ms

stopCount: 15

Stream Messages:

{"chunk": 1, "records": 1000, "progress": 10}
{"chunk": 2, "records": 2000, "progress": 20}
...
{"chunk": 10, "records": 10000, "progress": 100, "downloadUrl": "..."}
🔍
Live Search Results

When user searches, results arrive progressively.

Configuration:

Pattern: search (CONTAINS)

Initial Response: {"searching": true}

Interval: 800ms

stopAfter: 10000ms

stopCount: 10

Stream Messages:

{"results": [{"id": 1, "title": "Result 1"}]}
{"results": [{"id": 2, "title": "Result 2"}]}
{"results": [{"id": 3, "title": "Result 3"}]}
...
{"done": true, "totalResults": 10}

Complete Example: Video Upload & Processing

A real video upload scenario. User types "process video.mp4", upload starts, progress arrives, encoded, completed:

Configuration

Path: /api/video-process

Mode: Triggered Streaming

Trigger Pattern:

Incoming Pattern: ^process (.*)$

Match Type: REGEX

Initial Response:

{
  "status": "processing_started",
  "jobId": "job-abc123",
  "filename": "video.mp4",
  "timestamp": 1234567890
}

Stream Configuration:

Interval: 1000ms

stopAfter: 30000ms (30 seconds)

stopCount: 15 messages

Stream Messages (15 messages):

Message #1 (T+1s):

{
  "stage": "uploading",
  "progress": 10,
  "message": "Uploading file..."
}

Message #2 (T+2s):

{
  "stage": "uploading",
  "progress": 25,
  "message": "Uploading file..."
}

Message #3 (T+3s):

{
  "stage": "uploading",
  "progress": 50,
  "message": "Upload in progress..."
}

Message #4 (T+4s):

{
  "stage": "uploading",
  "progress": 75,
  "message": "Almost uploaded..."
}

Message #5 (T+5s):

{
  "stage": "uploaded",
  "progress": 100,
  "message": "Upload complete!"
}

Message #6 (T+6s):

{
  "stage": "analyzing",
  "progress": 100,
  "message": "Analyzing video..."
}

Message #7 (T+7s):

{
  "stage": "encoding",
  "progress": 15,
  "message": "Encoding started..."
}

Message #8 (T+8s):

{
  "stage": "encoding",
  "progress": 30,
  "message": "Encoding 30%..."
}

Message #9 (T+9s):

{
  "stage": "encoding",
  "progress": 50,
  "message": "Encoding 50%..."
}

Message #10 (T+10s):

{
  "stage": "encoding",
  "progress": 70,
  "message": "Encoding 70%..."
}

Message #11 (T+11s):

{
  "stage": "encoding",
  "progress": 90,
  "message": "Almost done..."
}

Message #12 (T+12s):

{
  "stage": "encoding",
  "progress": 100,
  "message": "Encoding complete!"
}

Message #13 (T+13s):

{
  "stage": "finalizing",
  "progress": 100,
  "message": "Finalizing..."
}

Message #14 (T+14s):

{
  "stage": "thumbnail",
  "progress": 100,
  "message": "Generating thumbnail..."
}

Message #15 (T+15s):

{
  "stage": "complete",
  "progress": 100,
  "message": "All done!",
  "videoUrl": "https://cdn.example.com/video-abc123.mp4",
  "thumbnailUrl": "https://cdn.example.com/thumb-abc123.jpg"
}

đŸŽŦ Timeline:

  1. T=0s: User sends "process video.mp4"
  2. T=0s: Initial response sent immediately
  3. T=1s: Message #1 (Upload 10%)
  4. T=2s: Message #2 (Upload 25%)
  5. ...
  6. T=15s: Message #15 (Complete!) → Stream stops (stopCount reached)
  7. Total duration: 15 seconds (stopCount came first, didn't reach stopAfter 30s)
Client Code Example:
const ws = new WebSocket('ws://localhost:5678/api/video-process');

ws.onopen = () => {
    // Trigger stream
    ws.send('process video.mp4');
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);

    if (data.status === 'processing_started') {
        showProgressBar();
        console.log('Job ID:', data.jobId);
    } else if (data.stage) {
        updateProgress(data.progress, data.message);

        if (data.stage === 'complete') {
            hideProgressBar();
            showSuccessMessage(data.videoUrl);
            ws.close();
        }
    }
};

// Output:
// Job ID: job-abc123
// [Progress: 10%] Uploading file...
// [Progress: 25%] Uploading file...
// ...
// [Progress: 100%] All done!
// Video URL: https://cdn.example.com/video-abc123.mp4

Stream Locking (Important!)

A critical feature in Triggered Streaming: New trigger messages are ignored while a stream is active!

âš ī¸ Why?

To prevent multiple streams from starting simultaneously. Otherwise, messages would get mixed up and it would be unclear which stream they belong to.

Scenario:

  1. T=0s: User sends "start" → Stream 1 starts
  2. T=2s: User sends "start" again → IGNORED! (Stream 1 still active)
  3. T=15s: Stream 1 stops (stopAfter or stopCount)
  4. T=17s: User sends "start" → Stream 2 starts (Stream 1 finished, now accepted)

💡 Testing Tip: Send multiple trigger messages while stream is active to test the lock mechanism. You should see "Ignoring message (stream active)" in backend logs!

Dynamic Configuration

⚡Live Updates (No Restart!)

You can change trigger patterns, stream messages, intervals, and stop conditions while the server is running!

✓Change interval → Applied immediately in active stream
✓Add stream message → Used in next cycle
✓Change stopAfter/stopCount → Applied to active stream
✓Change pattern → Takes effect for new triggers

Example Scenario:

  1. Stream started, interval: 2000ms, stopAfter: 30000ms
  2. After 5 seconds you changed interval to 1000ms
  3. Active stream immediately switched to 1s interval
  4. You reduced stopAfter to 15000ms
  5. Stream stopped at 15 seconds (new stopAfter value applied)

Best Practices

✅ Always send initial response

Immediately notify the client that processing has started - critical for UX!

✅ Make progress linear

Use predictable increments like 0, 20, 40, 60, 80, 100.

✅ Add "done" flag in final message

Let client know stream is finished: {"done": true}

✅ Always set stopAfter

Required field, specify maximum duration (max 10 minutes).

✅ Control message count with stopCount

For progress scenarios where message count is known (0-100 = 10 messages), use stopCount.

❌ Don't add too many stream messages

5-20 messages is sufficient, they repeat because it's circular.

❌ Don't set stopAfter too large

10-60 seconds is sufficient for testing, max 10 minutes.

Advanced Tips

💡 Multiple Trigger Patterns: Define different streams for different triggers. Example: "upload" → upload stream, "process" → processing stream.

💡 Empty Pattern Trick: If you leave pattern empty, EVERY message starts a stream. Perfect for "first message triggers" behavior.

💡 Stream Lock Testing: Send 5-10 messages while stream is active to test the lock mechanism. Watch the backend logs!

💡 Progressive Content: To simulate AI generation, add one word in each message, combine on the client to show full text.

💡 Error Simulation: Test client's error handling by sending error messages mid-stream:{"error": "Connection lost", "retry": true}

🔄 Lifecycle Events

Send automatic messages throughout the WebSocket connection lifecycle. Welcome messages when clients connect, goodbye messages when disconnecting, and more!

What are Lifecycle Events?

Lifecycle Events are events that are automatically triggered at specific moments during a WebSocket connection. Mocklantis currently supports the onConnect event.

Supported Events:
ACTIVE

onConnect

Triggered when client connects to the WebSocket

FUTURE

onDisconnect

When client disconnects (may be added in the future)

FUTURE

onError

When an error occurs in the connection (may be added in the future)

onConnect Event

Automatically sends a message when the client connects to the WebSocket. Ideal for welcome messages, session information, initial state, and similar data.

đŸ’ŦMessage

The message to send when the client connects. Can be plain text or JSON.

Plain Text Example:

Welcome to the chat! You are now connected.

JSON Example:

{
  "event": "connected",
  "sessionId": "sess-abc123",
  "timestamp": 1234567890,
  "message": "Welcome! You are now connected."
}
âąī¸Delay (Optional)

How many milliseconds after connection to send the message. Default: 0ms (instant)

0ms→ Send instantly (default)
500ms→ After 0.5 seconds
1000ms→ After 1 second
3000ms→ After 3 seconds

💡 When to use delay?

  • To simulate server "preparation" time
  • To test connection handshake delay
  • UX: To show "Connecting..." animation

Use Cases

The onConnect event can be used for many scenarios:

👋
Welcome Message

Notify the user that the connection was successful.

Configuration:

Message: Welcome to our chat! You are now online.

Delay: 0ms

đŸŽĢ
Session Information

Send session ID, user info, and connection details to the client.

Configuration:

Message:

{
  "event": "session_created",
  "sessionId": "sess-abc123",
  "userId": "user-456",
  "connectedAt": 1234567890,
  "expiresIn": 3600
}

Delay: 0ms

📊
Initial State / Data

Send initial data to the client when connection is established.

Configuration:

Message:

{
  "type": "initial_state",
  "data": {
    "unreadMessages": 5,
    "onlineUsers": 42,
    "serverVersion": "1.2.3"
  }
}

Delay: 0ms

✅
Server Status

Inform about server health, capabilities, and feature flags.

Configuration:

Message:

{
  "server": {
    "status": "healthy",
    "version": "2.1.0",
    "features": ["chat", "files", "video"],
    "maintenance": false
  }
}

Delay: 0ms

🔐
Authentication Confirmation

Confirm that authentication was successful and the token is valid.

Configuration:

Message:

{
  "auth": "success",
  "user": {
    "id": "user-123",
    "username": "john_doe",
    "role": "premium"
  },
  "permissions": ["read", "write", "admin"]
}

Delay: 500ms (auth check simulation)

📖
Instructions / Help

Tell the user how to use the system and what commands are available.

Configuration:

Message:

Welcome! Available commands:
/help - Show this message
/status - Check server status
/users - List online users
/quit - Disconnect

Delay: 1000ms (for connection animation)

Timeline Example

See how the onConnect event works with different modes:

Scenario: Conversational Mode + onConnect

Configuration:

  • â€ĸ Mode: Conversational
  • â€ĸ onConnect Message: "Welcome! Send 'hello' to start."
  • â€ĸ onConnect Delay: 500ms
  • â€ĸ Pattern 1: "hello" → "Hi there!"

Timeline:

  1. T=0ms: Client connects to WebSocket
  2. T=500ms: onConnect message arrives: "Welcome! Send 'hello' to start."
  3. T=2000ms: User sends "hello"
  4. T=2000ms: Pattern matches, response sent: "Hi there!"
Scenario: Streaming Mode + onConnect

Configuration:

  • â€ĸ Mode: Streaming
  • â€ĸ onConnect Message: "Stream starting..."
  • â€ĸ onConnect Delay: 0ms
  • â€ĸ Streaming Interval: 2000ms
  • â€ĸ Stream Messages: ["Message 1", "Message 2", "Message 3"]

Timeline:

  1. T=0ms: Client connects to WebSocket
  2. T=0ms: onConnect message arrives immediately: "Stream starting..."
  3. T=0ms: Streaming timer starts
  4. T=2000ms: Stream message #1: "Message 1"
  5. T=4000ms: Stream message #2: "Message 2"
  6. T=6000ms: Stream message #3: "Message 3"
  7. T=8000ms: Back to Message 1 (circular)
Scenario: Triggered Streaming + onConnect

Configuration:

  • â€ĸ Mode: Triggered Streaming
  • â€ĸ onConnect Message: {"ready": true, "instruction": "Send 'start' to begin"}
  • â€ĸ onConnect Delay: 1000ms
  • â€ĸ Trigger Pattern: "start"
  • â€ĸ Initial Response: "Processing..."
  • â€ĸ Stream Interval: 1000ms

Timeline:

  1. T=0ms: Client connects to WebSocket
  2. T=1000ms: onConnect message arrives: {"ready": true, ...}
  3. T=3000ms: User sends "start"
  4. T=3000ms: Initial response sent immediately: "Processing..."
  5. T=4000ms: Stream message #1
  6. T=5000ms: Stream message #2
  7. ...

Best Practices

✅ Always add an onConnect message

Inform the client that the connection was successful - important for UX!

✅ Use JSON format

Sending structured data makes client parsing easier.

✅ Add an event type field

{"event": "connected", ...} helps the client easily distinguish message types.

✅ Simulate realistic latency with delay

Add 500-1000ms delay to simulate authentication checks.

✅ Include useful info

Add information like session ID, timestamp, server version.

❌ Don't send overly long messages

onConnect should be short and concise, use a separate endpoint for large data.

❌ Don't set delay too high

More than 3 seconds keeps the user waiting, 1-2 seconds is ideal.

Comprehensive Example: Chat Application

onConnect configuration for a production-ready chat application:

Configuration

Path: /chat/room-123

Mode: Conversational

onConnect Event:

Delay: 800ms

Message:

{
  "event": "room_joined",
  "roomId": "room-123",
  "roomName": "General Chat",
  "sessionId": "sess-abc456",
  "user": {
    "id": "user-789",
    "username": "john_doe",
    "avatar": "https://example.com/avatar.jpg"
  },
  "stats": {
    "onlineUsers": 42,
    "totalMessages": 1250
  },
  "capabilities": {
    "canSendImages": true,
    "canSendFiles": true,
    "maxFileSize": 10485760
  },
  "commands": [
    "/help - Show available commands",
    "/users - List online users",
    "/history - Show message history"
  ],
  "timestamp": 1234567890
}
Client Implementation
const ws = new WebSocket('ws://localhost:5678/chat/room-123');

ws.onopen = () => {
    console.log('Connecting to chat room...');
    showLoadingSpinner();
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);

    if (data.event === 'room_joined') {
        // onConnect message received!
        hideLoadingSpinner();

        // Display welcome info
        showWelcomeMessage(`Welcome to ${data.roomName}!`);

        // Update UI with room stats
        updateOnlineCount(data.stats.onlineUsers);

        // Store session info
        localStorage.setItem('sessionId', data.sessionId);

        // Display available commands
        showCommandsPanel(data.commands);

        console.log('Connected to room:', data.roomId);
        console.log('Online users:', data.stats.onlineUsers);
    } else {
        // Handle other message types (chat messages, etc.)
        handleChatMessage(data);
    }
};

// Expected Console Output:
// > Connecting to chat room...
// (800ms delay...)
// > Connected to room: room-123
// > Online users: 42

Tips

💡 Loading States: Use delay to test your "Connecting..." or "Authenticating..." loading states.

💡 Error Testing: Test your connection failure handling by sending an error in the onConnect message:{"error": "Room full"}

💡 Version Checking: Send the server version in onConnect to test client version compatibility checks.

💡 Initial State Sync: Send initial data with onConnect to test the client's first-render optimization.

đŸ”Ĩ Advanced Options & Tips

Advanced features, debugging techniques, troubleshooting, and production-level test strategies for mastering Mocklantis!

đŸ‘Ĩ Multi-Client Testing

Simulate real-world scenarios by testing with multiple clients:

🌐Multiple Browser Tabs

The easiest method: Open clients in different tabs of the same browser.

Test Steps:

  1. Connect WebSocket client in the first tab
  2. Open a second tab, connect to the same endpoint
  3. Open a third tab, connect to the same endpoint again
  4. Monitor messages with console.log in each tab
  5. Streaming: Does each tab receive an independent stream? ✓
🔀Different Browsers

Perform cross-browser testing with Chrome, Firefox, and Safari.

Why is it important?

  • WebSocket implementations may differ
  • Reconnection logic varies by browser
  • Message handling timings are different
📱Mobile + Desktop

Realistic multi-platform testing with phone + computer.

Setup:

  1. Start Mocklantis server on your computer
  2. Find your IP address (e.g., 192.168.1.5)
  3. Open browser on your phone
  4. Connect to ws://192.168.1.5:5678/your-path
  5. Test desktop + mobile simultaneously!

đŸŽ¯ Advanced Test Scenarios

Advanced strategies for production-level test scenarios:

🔄
Reconnection Logic Testing

Simulate network loss and verify the client reconnects.

Test Steps:

  1. Connect client, start stream
  2. Stop the Mocklantis server
  3. Reconnection logic is triggered in the client
  4. Restart the server
  5. Does the client reconnect automatically? ✓
  6. Does the stream continue? ✓
⚡
Race Condition Testing

Catch race conditions with rapid sequential messages.

Test Code:

// Rapid fire messages
for (let i = 0; i < 10; i++) {
    ws.send(`message ${i}`);
}

// Does the client handle it properly?
// Is message order preserved?
// Does the UI freeze?
💾
Memory Leak Testing

Run for a long time and check for memory leaks.

Test Strategy:

  1. Start streaming mode (interval: 1000ms)
  2. Open Browser DevTools → Performance → Memory
  3. Run for 10-15 minutes
  4. Does memory usage increase or stay constant?
  5. Disconnect → Reconnect
  6. Is memory cleaned up? ✓
🚨
Error Recovery Testing

Test error handling by sending invalid JSON and malformed data.

Test Messages:

// Invalid JSON
ws.send('{invalid json}');

// Huge message
ws.send('x'.repeat(1000000));

// Special characters
ws.send('\x00\x01\x02');

// Does the client crash?
// Does it show an error message?
// Can it recover?
🔀
Concurrent Operations

Send messages and receive streams simultaneously.

Scenario:

  • Conversational Mode + onConnect active
  • onConnect message arrives
  • User sends a message simultaneously
  • Receives response
  • Sends another message simultaneously
  • Are all messages handled correctly? ✓
📊
Load Testing

Perform stress tests with multiple clients.

Test Script:

// Node.js script
const WebSocket = require('ws');

// Create 50 clients
for (let i = 0; i < 50; i++) {
    const ws = new WebSocket('ws://localhost:5678/chat');
    ws.on('open', () => {
        console.log(`Client ${i} connected`);
    });
}

// Does the UI stay responsive?
// Is the server stable?
// Are messages distributed correctly?

🔧 Troubleshooting

Common problems and solutions:

❌ Can't connect

  • Is the server running? Are there logs in the terminal?
  • Is the port correct? (ws://localhost:5678/path)
  • Is the path correct? (does it start with /)?
  • Is the firewall blocking it?

âš ī¸ Pattern not matching

  • Is the match type correct? (EXACT is very strict)
  • Is there whitespace? ("hello " ≠ "hello")
  • Case-sensitive! ("Hello" ≠ "hello")
  • JSON_PATH: Does the field actually exist?
  • REGEX: Is the syntax correct? Test it

đŸ’Ŧ Not receiving messages

  • Is the ws.onmessage handler defined?
  • Are there any errors in the console?
  • There might be a JSON.parse error, add try-catch
  • Is there "Sent response" in the backend log?

🔄 Stream not starting

  • Streaming: Are messages empty?
  • Triggered: Make sure you sent the trigger message
  • Triggered: Is the stream already active? (check logs)
  • Are interval and stopAfter set correctly?

⚡ Slow performance

  • Is the interval too low? (min 100ms)
  • Are there too many patterns? (10-20 ideal)
  • Is the regex too complex?
  • Is the message size too large?
  • Are too many clients connected?

💎 Pro Tips & Tricks

💡 Tip #1: Pattern Priority Testing
Add 2 patterns that match the same message. Does the first one work? Test if priority is correct.

💡 Tip #2: Timestamp in Every Message
Add timestamps to responses to measure client-side latency.

💡 Tip #3: Message ID
Give each message a unique ID to test duplicate detection.

💡 Tip #4: Error Messages
Test error handling by sending {"error": "...", "code": 500} in the middle of a stream.

💡 Tip #5: Progressive Enhancement
Start with simple patterns, increase complexity as you verify they work.

💡 Tip #6: Multiple Endpoints
Use different paths for different features: /chat, /notifications, /data

💡 Tip #7: Browser DevTools Network Tab
You can see WebSocket frames in the Network tab, check the raw data.

💡 Tip #8: Save Configurations
Export your Mocklantis configs as JSON (future feature), share with your team.

SSE Endpoints

Simulate real-time server-to-client streaming with Server-Sent Events. Perfect for live notifications, AI streaming responses, real-time feeds, and more!

What is SSE?

Server-Sent Events (SSE) is a standard that enables servers to push real-time updates to clients over HTTP. Unlike WebSockets, SSE is unidirectional (server-to-client only), making it simpler and perfect for scenarios where the client only needs to receive data.

SSE vs WebSocket
FeatureSSEWebSocket
DirectionServer → Client (unidirectional)Bidirectional
ProtocolHTTP/HTTPSWS/WSS
Auto ReconnectBuilt-inManual
Event IDsBuilt-inManual
ComplexitySimpleMore complex

When to use SSE: When you need real-time updates from server to client without client sending data back. Examples: notifications, live feeds, AI streaming responses, stock tickers.

Quick Start

Creating an SSE endpoint takes just 3 steps:

  1. Set the path: /events
  2. Configure streaming: Set interval and optional retry
  3. Add messages: Create the events to be streamed
Example: Basic Notification Stream

Path: /notifications

Interval: 3000ms

Messages:

Message 1: {"type": "info", "message": "New user signed up"}
Message 2: {"type": "alert", "message": "Server CPU at 80%"}
Message 3: {"type": "success", "message": "Backup completed"}

Path Configuration

Define the access path for your SSE endpoint. The path must always start with /.

Example Paths:
✓/events- General event stream
✓/api/v1/notifications- Notification stream
✓/stream/prices- Price updates
✓/chat/completions- AI response streaming

✅ Live Updates: You can change the path while the server is running - active connections are preserved!

SSE Protocol Format

Mocklantis generates SSE messages following the official specification. Here's how the wire format looks:

Wire Format:
id: 1
event: notification
data: {"type": "info", "message": "Hello!"}

id: 2
event: notification
data: {"type": "alert", "message": "Warning!"}
SSE Fields:
id:

Event ID

Unique identifier for reconnection support

event:

Event Type

Custom event name (defaults to "message")

data:

Event Data

The actual message content (JSON, text, etc.)

retry:

Retry Interval

Client reconnection delay in milliseconds

💡 Multi-line Data: When your data contains multiple lines, each line is automatically prefixed with data:. The client reconstructs the original content.

Streaming Settings

âąī¸Interval (ms)

Time between messages in milliseconds. This is the base timing for your stream.

500ms→ Fast (2 messages per second)
1000ms→ Normal (1 message per second)
5000ms→ Slow (1 message per 5 seconds)
🔄Retry (ms) - Optional

Tells the client how long to wait before attempting to reconnect if the connection drops. This value is sent once when the connection is established.

1000ms→ Quick reconnect (1 second)
3000ms→ Default browser behavior
10000ms→ Conservative (10 seconds)
🔖Support Last-Event-ID

When enabled, clients can resume from where they left off after a disconnection.

How it works:

  1. Client connects and receives events with IDs (1, 2, 3...)
  2. Connection drops at event ID 5
  3. Client reconnects with header: Last-Event-ID: 5
  4. Server resumes from event ID 6

âš ī¸ Important: For this to work, you must assign unique IDs to your messages!

Messages Configuration

Configure the messages that will be streamed to clients. Messages are sent sequentially and loop back to the beginning when the list ends.

Message Fields:
Event Type- optional

Custom event name. Clients can listen for specific event types using addEventListener().

Examples: message, notification, update, error

Event ID- optional

Unique identifier for the event. Required for Last-Event-ID reconnection support.

Formats: 1, 2, 3 (sequential), uuid, timestamp

Data- required

The actual content of the event. Can be JSON, plain text, XML, or any format.

{"type": "notification", "message": "Hello!"}
Delay (ms)- optional

Additional delay before sending this specific message. Added on top of the interval.

Example: Interval=1000ms, Delay=5000ms → This message waits 6 seconds total

💡 Random Variables: You can use random variables in your data! Use {{$randomInt}}, {{$randomEmail}}, etc. to generate dynamic content.

On Connect Message

Optionally send a welcome message immediately when a client connects, before the regular stream starts.

Use Cases:
✓Send connection confirmation
✓Provide initial state or configuration
✓Send authentication acknowledgment
✓Deliver cached/historical data before live stream

Example On Connect Message:

{
  "status": "connected",
  "server": "mocklantis-sse-v1",
  "timestamp": "2024-01-15T10:30:00Z"
}

Connection Examples

Connect to your SSE endpoint using these examples:

JavaScript (EventSource)
const eventSource = new EventSource('http://localhost:5678/events');

// Listen for default "message" events
eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
};

// Listen for custom event types
eventSource.addEventListener('notification', (event) => {
    console.log('Notification:', event.data);
});

// Handle connection events
eventSource.onopen = () => console.log('Connected!');
eventSource.onerror = () => console.log('Error/Reconnecting...');

// Close connection
// eventSource.close();
curl
# Basic connection
curl -N http://localhost:5678/events

# With Last-Event-ID (resume from event 5)
curl -N -H "Last-Event-ID: 5" http://localhost:5678/events

# The -N flag disables buffering for real-time output
Python (sseclient)
import sseclient
import requests

url = 'http://localhost:5678/events'
response = requests.get(url, stream=True)
client = sseclient.SSEClient(response)

for event in client.events():
    print(f'Event: {event.event}')
    print(f'ID: {event.id}')
    print(f'Data: {event.data}')
    print('---')
Node.js (eventsource)
import EventSource from 'eventsource';

const es = new EventSource('http://localhost:5678/events');

es.onmessage = (event) => {
    console.log('Data:', event.data);
};

es.addEventListener('notification', (event) => {
    console.log('Notification:', JSON.parse(event.data));
});

Real-World Use Cases

SSE is used across many industries for real-time data delivery. Here are practical examples:

🤖
AI/LLM Response Streaming

Mock ChatGPT, Claude, or any AI API that streams responses token by token.

Configuration:

Path: /v1/chat/completions

Interval: 50ms (fast token streaming)

Example Messages (OpenAI format):

{"choices":[{"delta":{"content":"Hello"}}]}
{"choices":[{"delta":{"content":" there"}}]}
{"choices":[{"delta":{"content":"!"}}]}
{"choices":[{"delta":{"content":" How"}}]}
{"choices":[{"delta":{"content":" can"}}]}
{"choices":[{"delta":{"content":" I"}}]}
{"choices":[{"delta":{"content":" help"}}]}
{"choices":[{"delta":{"content":"?"}}]}
[DONE]

Industry: AI/ML platforms, chatbots, coding assistants, content generation

🔔
Real-Time Notifications

Push notifications for social apps, e-commerce, or enterprise dashboards.

Configuration:

Path: /api/notifications

Interval: 5000ms

Example Messages:

{"type": "like", "user": "john", "message": "liked your post"}
{"type": "comment", "user": "jane", "message": "commented on your photo"}
{"type": "follow", "user": "mike", "message": "started following you"}
{"type": "order", "message": "Your order #1234 has shipped"}

Industry: Social media, e-commerce, SaaS platforms, mobile apps

📈
Stock & Crypto Prices

Real-time price feeds for trading platforms and financial dashboards.

Configuration:

Path: /stream/prices

Interval: 1000ms

Example Messages:

{"symbol": "BTC", "price": 42350.75, "change": "+2.5%"}
{"symbol": "ETH", "price": 2245.30, "change": "+1.8%"}
{"symbol": "AAPL", "price": 178.25, "change": "-0.3%"}

Industry: FinTech, trading platforms, crypto exchanges, banking

âšŊ
Live Sports Scores

Real-time match updates, scores, and statistics.

Configuration:

Path: /live/match/123

Interval: 3000ms

Example Messages:

{"minute": 15, "score": "1-0", "event": "GOAL", "team": "home"}
{"minute": 32, "score": "1-1", "event": "GOAL", "team": "away"}
{"minute": 45, "event": "HALFTIME"}
{"minute": 78, "score": "2-1", "event": "GOAL", "team": "home"}

Industry: Sports betting, live score apps, sports media

đŸŒĄī¸
IoT Sensor Data

Stream sensor readings from IoT devices - temperature, humidity, motion, etc.

Configuration:

Path: /sensors/room-1

Interval: 2000ms

Example Message:

{
  "sensorId": "TEMP-001",
  "temperature": 23.5,
  "humidity": 65,
  "pressure": 1013.25,
  "timestamp": "2024-01-15T10:30:00Z"
}

Industry: Smart home, industrial IoT, agriculture, healthcare monitoring

📋
Log Streaming

Real-time log output for monitoring dashboards and debugging tools.

Configuration:

Path: /logs/stream

Interval: 500ms

Event Types: info, warn, error

Example Messages:

{"level": "info", "message": "User login: [email protected]"}
{"level": "warn", "message": "High memory usage: 85%"}
{"level": "error", "message": "Database connection timeout"}
{"level": "info", "message": "Request processed in 234ms"}

Industry: DevOps, monitoring tools, debugging platforms, observability

📰
News & Social Feeds

Real-time content updates for news sites, social platforms, and content aggregators.

Configuration:

Path: /feed/latest

Interval: 10000ms

Example Messages:

{"type": "article", "title": "Breaking: New Tech Release", "author": "TechNews"}
{"type": "tweet", "user": "@elonmusk", "content": "Exciting announcement..."}
{"type": "post", "user": "jane_doe", "content": "Just shipped v2.0!"}

Industry: Media, journalism, social networks, content platforms

âŗ
Progress & Status Updates

Track long-running operations like file uploads, data processing, or deployments.

Configuration:

Path: /jobs/123/status

Interval: 2000ms

Example Messages:

{"progress": 10, "status": "Initializing..."}
{"progress": 30, "status": "Processing files..."}
{"progress": 60, "status": "Analyzing data..."}
{"progress": 90, "status": "Finalizing..."}
{"progress": 100, "status": "Complete!", "result": "success"}

Industry: CI/CD, file hosting, data processing, cloud services

Best Practices

✅ Use appropriate intervals

Match your production environment. AI streaming: 50-100ms. Notifications: 3-5s. Metrics: 1-2s.

✅ Add Event IDs for reliability

Enable Last-Event-ID support so clients can resume after disconnection.

✅ Use Event Types for filtering

Categorize events so clients can subscribe to specific types they care about.

✅ Include timestamps

Add timestamps to messages for client-side freshness checks.

✅ Test reconnection scenarios

Verify your client handles reconnection gracefully with Last-Event-ID.

❌ Don't use too few messages

Add variety - 5-10+ messages create more realistic simulations.

❌ Don't forget the retry field

Set a reasonable retry interval so clients don't hammer your server on reconnection.

Dynamic Updates

⚡Live Configuration Changes

Mocklantis allows real-time configuration changes without server restart or client disconnection!

✓Change interval → Takes effect immediately
✓Add/remove messages → Active in next cycle
✓Edit message content → Updates instantly
✓Active connections preserved → Clients stay connected

Example Scenario:

  1. Server running, 5 clients connected, interval: 2000ms
  2. You change interval to 500ms
  3. All clients stay connected, new interval applies immediately
  4. You add 3 new messages
  5. New messages appear in the stream on next cycle

Testing Tips

💡 Browser DevTools: Open Network tab, filter by "EventStream" to see SSE connections and inspect incoming messages in real-time.

💡 Multiple Clients: Open multiple browser tabs to verify each client receives their own independent stream.

💡 Test Reconnection: Kill the connection (curl Ctrl+C) and reconnect with Last-Event-ID header to verify resume functionality.

💡 Verify Event Types: Use different event types and ensure your client'saddEventListener() calls receive the correct events.

Summary

Mocklantis SSE provides a complete Server-Sent Events implementation with all the features you need:

Features:

  • ✓ Event Types
  • ✓ Event IDs
  • ✓ Per-message Delay
  • ✓ Retry Interval
  • ✓ Last-Event-ID Support
  • ✓ On Connect Message
  • ✓ Random Variables

Benefits:

  • ✓ Zero Config Complexity
  • ✓ Live Updates
  • ✓ No Server Restart
  • ✓ Connection Preserved
  • ✓ Protocol Compliant
  • ✓ Production-Ready

Import & Export

Mocklantis provides powerful import and export features to help you quickly create endpoints from existing APIs or save your work for later use. Access these features from the Import & Export button in the top-right corner of the workspace.

đŸ“ĨImport from Curl

Convert any curl command into a fully configured mock endpoint. Perfect for replicating existing API calls.

📍 How to Import from Curl:

  1. Click the Import & Export button in the top-right corner
  2. Select "Import from Curl" from the dropdown menu
  3. Paste your curl command in the text area
  4. Click "Import"
  5. Mocklantis will automatically detect:
    • HTTP method (GET, POST, PUT, DELETE, etc.)
    • Endpoint path and query parameters
    • Request headers (Authorization, Content-Type, etc.)
    • Request body (if present)
  6. A new endpoint will be created with all detected parameters

Example Curl Command:

curl -X POST "http://localhost:3000/api/users?page=1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer token123" \
  --data '{"name":"John","email":"[email protected]"}'

What gets imported:

  • Method: POST
  • Path: /api/users
  • Query Param: page=1 (type: number)
  • Request Headers: Content-Type, Authorization
  • Request Body: {"name":"John","email":"[email protected]"}

💡 Pro Tip: You can copy curl commands directly from your browser's Network tab or API documentation!

📂Import from .mock

Load previously exported endpoint configurations from .mock files. Great for sharing endpoints or backing up your work.

📍 How to Import from .mock:

  1. Click the Import & Export button in the top-right corner
  2. Select "Import from .mock" from the dropdown menu
  3. Choose a .mock file from your computer
  4. The endpoint configuration will be loaded with all settings:
    • Method, path, and status code
    • Request and response headers
    • Request and response body
    • Query parameters and path variables
    • Response delay
  5. The imported endpoint will be added to your current server

Use Cases:

  • Team Collaboration: Share endpoint configurations with teammates
  • Version Control: Commit .mock files to Git for version tracking
  • Backup & Restore: Save your work and restore it later
  • Quick Setup: Import pre-configured endpoints for common APIs

💡 Pro Tip: .mock files are human-readable text files. You can edit them directly if needed!

💾Export as .mock

Save your endpoint configuration to a .mock file. This allows you to backup, share, or version control your mock endpoints.

📍 How to Export as .mock:

  1. Select the endpoint you want to export
  2. Click the Import & Export button in the top-right corner
  3. Select "Export as .mock" from the dropdown menu
  4. Choose a location and filename for the .mock file
  5. The file will be saved with all endpoint configuration:
    • Complete endpoint definition
    • All headers and parameters
    • Request/response bodies
    • Validation rules

âš ī¸ Important Notes:

  • Only the currently selected endpoint is exported (not the entire server)
  • If no endpoint is selected, the first endpoint will be exported
  • The export button is disabled if the server has no endpoints
  • .mock files are portable - they work across different computers and Mocklantis versions

💡 Best Practice: Export endpoints regularly to create backups, especially before making major changes!

🔄Complete Workflow Example

Scenario: Copying an endpoint from production to Mocklantis

  1. Step 1: Open your browser's Developer Tools (F12)
  2. Step 2: Go to the Network tab and make a request to the API
  3. Step 3: Right-click the request → Copy → Copy as cURL
  4. Step 4: In Mocklantis, click Import & Export → "Import from Curl"
  5. Step 5: Paste the curl command and click Import
  6. Step 6: Customize the response body with your mock data
  7. Step 7: Start the server and test your mock endpoint
  8. Step 8: Export as .mock to save for future use

đŸŽ¯ Result: You've successfully created a mock endpoint that mirrors your production API, and you can now share it with your team or reuse it in different projects!

Pro Tips

💡 Use curl import to quickly replicate any API call without manual configuration

💡 Store .mock files in version control (Git) to track endpoint changes over time

💡 Create a library of .mock files for commonly used endpoints across projects

đŸŽ¯ Combine import and export to migrate endpoints between different Mocklantis instances

✅ After importing, always review and customize the response body to match your testing needs

Logging & Request Monitoring

Mocklantis provides real-time request logging and monitoring for all HTTP requests hitting your mock servers. The Logs panel shows you every detail of incoming requests and outgoing responses, similar to browser DevTools Network tab.

Located at the bottom of the application, the Logs panel automatically captures all traffic and displays it in real-time as requests come in.

📍Accessing the Logs Panel

  1. The Logs panel is located at the bottom of the application
  2. Click on the "Logs" header to expand/collapse the panel
  3. The panel shows a count of total logs captured: Logs (47)
  4. You can resize the panel by dragging the top border up or down

📊What Gets Logged

Every HTTP request to your mock servers is automatically logged with the following information:

Timestamp:Exact time the request was received (HH:MM:SS)
Server Info:Server name and port (e.g., "My API:8021")
HTTP Method:GET, POST, PUT, DELETE, PATCH, OPTIONS, etc.
Request Path:Full URL path including query parameters
Status Code:HTTP response status (200, 404, 500, etc.)
Duration:Response time in milliseconds
Request Headers:All headers sent by the client
Request Body:Request payload (JSON, XML, text, etc.)
Response Headers:All headers returned by the mock server
Response Body:Response payload sent back to the client

🔍Inspecting Request Details

Click on any log entry to expand it and view full details. The expanded view provides four tabs:

Request Headers

View all headers sent by the client, including Content-Type, Authorization, User-Agent, etc. Useful for debugging authentication issues or content negotiation.

Request Body

Inspect the payload sent by the client. For JSON requests, you'll see the formatted JSON. This helps verify that clients are sending the correct data structure.

Response Headers

See all headers returned by your mock, including Content-Type, CORS headers, custom headers, etc. Verify that your response headers are configured correctly.

Response Body

View the exact response payload sent back to the client. Verify random variables were replaced, response body matches expectations, and JSON structure is correct.

🎨Visual Color Coding

Logs use color coding to help you quickly identify request types and response statuses:

HTTP Methods:

GETPOSTPUTDELETEPATCH

Status Codes:

2xxSuccess (green)
3xxRedirection (blue)
4xxClient Error (orange)
5xxServer Error (red)

đŸ’ŧReal-World Use Cases

1. Debugging Authentication Issues

When testing login flows, check the Request Headers to verify the Authorization token is being sent correctly. Check the Response Body to ensure your mock is returning the expected token format.

2. Verifying CORS Configuration

Look at Response Headers to confirm CORS headers (Access-Control-Allow-Origin, etc.) are present. Check for OPTIONS requests (preflight) in the logs to ensure they're handled correctly.

3. Testing Random Variables

Expand logs and view Response Body to verify random variables like {{random.uuid}} are being replaced with actual values. Each request should show different random data.

4. Monitoring Response Times

Check the Duration (in milliseconds) for each request. If you've configured a response delay, verify it's working by checking the duration matches your configured delay.

5. Validating Request Matching

When using query parameter matching or header matching, inspect logs to see which endpoint was matched. Check Request Headers and query parameters to verify the matching logic is working as expected.

⚡Key Features

  • ✓Real-time Streaming: Logs appear instantly as requests come in, no refresh needed
  • ✓Auto-scroll: Panel automatically scrolls to show the latest logs
  • ✓Resizable Panel: Drag the top border to adjust panel height (150px - 500px)
  • ✓Collapsible: Click the header to show/hide logs panel
  • ✓Clear Logs: Remove all logs with a single click using the "Clear Logs" button
  • ✓Multi-server Support: Logs from all running servers appear in a single unified view
  • ✓Complete Request/Response Inspection: View every detail of HTTP transactions

Pro Tips

💡 Keep the Logs panel open during development to monitor all API traffic in real-time

💡 Use the timestamp to correlate logs with actions in your frontend application

💡 Check status codes - orange/red indicates errors that need attention

💡 Verify request bodies before investigating response issues - often the problem is in what the client sends

💡 Clear logs periodically to focus on recent requests and improve performance

💡 Use the duration to identify slow endpoints - if it's much higher than your configured delay, something's wrong

💡 For WebSocket endpoints, check the logs for the initial HTTP upgrade request

Need more help?

Check our FAQ for common questions or reach out to the community

Visit FAQ