Skip to main content
Yasumu includes a powerful scripting system powered by Tanxium, a custom JavaScript runtime built on Deno. Scripts allow you to manipulate requests, process responses, and create dynamic testing workflows using TypeScript.

What is Tanxium?

Tanxium is Yasumu’s embedded JavaScript runtime that executes scripts in a secure, isolated environment:

TypeScript native

Write scripts in TypeScript without compilation steps.

Deno-powered

Built on deno_runtime for security and modern APIs.

Isolated execution

Scripts run in Web Workers for safety and performance.

Node.js compatible

Supports common Node.js modules and APIs.

Script lifecycle

Scripts can execute at three different stages:
Pre-request scripts run before the HTTP request is sent:
export function onRequest(req, res) {
  // Modify request before sending
  req.headers.set('X-Timestamp', Date.now().toString());
  req.headers.set('X-Request-ID', crypto.randomUUID());
  
  // Access environment variables
  const apiKey = req.environment.get('API_KEY');
  req.headers.set('Authorization', `Bearer ${apiKey}`);
  
  console.log('Request prepared:', req.url);
}
Use cases:
  • Generate authentication tokens
  • Add dynamic headers or parameters
  • Modify request body
  • Log request details

Script context

Scripts receive two main objects:

Request object (req)

The request object provides access to request data and methods:
export function onRequest(req, res) {
  // Request properties
  console.log(req.method);    // HTTP method (GET, POST, etc.)
  console.log(req.url);        // Request URL
  console.log(req.headers);    // Headers Map
  console.log(req.body);       // Request body
  
  // Modify request
  req.headers.set('Custom-Header', 'value');
  req.headers.delete('Old-Header');
  
  // Access environment
  const apiUrl = req.environment.get('API_URL');
  const apiKey = req.environment.get('API_KEY');
  
  // Set environment values
  req.environment.set('LAST_REQUEST', Date.now());
  
  // Access workspace info
  console.log(req.workspace.name);
  console.log(req.workspace.id);
}

Response object (res)

The response object provides access to response data:
export function onResponse(req, res) {
  // Response properties
  console.log(res.status);      // HTTP status code
  console.log(res.statusText);  // Status message
  console.log(res.headers);     // Response headers Map
  console.log(res.body);        // Response body (string)
  
  // Parse JSON response
  const data = JSON.parse(res.body);
  console.log('Parsed data:', data);
  
  // Check response type
  const contentType = res.headers.get('Content-Type');
  if (contentType?.includes('application/json')) {
    const json = JSON.parse(res.body);
    // Process JSON data
  }
}

Creating custom responses

You can return custom responses without making actual HTTP requests:
export function onRequest(req, res) {
  // Return a mock response
  const mockResponse = new YasumuResponse(
    JSON.stringify({
      id: 123,
      name: 'Mock User',
      email: '[email protected]'
    }),
    {
      status: 200,
      statusText: 'OK',
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );
  
  return mockResponse;
}
When a script returns a YasumuResponse, the actual HTTP request is skipped, and the mock response is used instead.

Script examples

Generate authentication tokens dynamically:
export function onRequest(req, res) {
  // Basic authentication
  const username = req.environment.get('USERNAME');
  const password = req.environment.get('PASSWORD');
  
  if (username && password) {
    const credentials = `${username}:${password}`;
    const encoded = btoa(credentials);
    req.headers.set('Authorization', `Basic ${encoded}`);
  }
  
  // Bearer token
  const token = req.environment.get('AUTH_TOKEN');
  if (token) {
    req.headers.set('Authorization', `Bearer ${token}`);
  }
}

Environment access in scripts

Scripts have full access to environment variables and secrets:
export function onRequest(req, res) {
  // Get variables
  const apiUrl = req.environment.get('API_URL');
  const version = req.environment.get('API_VERSION');
  
  // Get secrets (same API)
  const apiKey = req.environment.get('API_KEY');
  
  // Set new values
  req.environment.set('LAST_REQUEST_TIME', Date.now());
  req.environment.set('REQUEST_COUNT', '1');
  
  // Check if variable exists
  if (req.environment.get('DEBUG') === 'true') {
    console.log('Debug mode enabled');
  }
}
Changes to environment variables in scripts are temporary and only persist for the current request execution. To make permanent changes, update the environment through the API.

Available APIs

Tanxium provides access to common JavaScript and Node.js APIs:
console.log('Message');
console.error('Error message');
console.warn('Warning');
console.info('Info');
console.debug('Debug');
console.assert(condition, 'Assertion message');
// Generate UUID
const id = crypto.randomUUID();

// Generate random values
const bytes = crypto.getRandomValues(new Uint8Array(16));
import { Buffer } from 'node:buffer';
import { createHmac } from 'node:crypto';

// Use Buffer
const encoded = Buffer.from('text').toString('base64');

// Use crypto
const hash = createHmac('sha256', 'secret')
  .update('data')
  .digest('hex');
const url = new URL(req.url);
console.log(url.hostname);
console.log(url.pathname);
console.log(url.searchParams.get('key'));
const now = Date.now();
const date = new Date();
const timestamp = date.toISOString();

Script execution flow

1

Parse script

The script is parsed and validated for syntax errors.
2

Create worker

A new Web Worker is created for isolated execution.
3

Load context

Request, response, and environment data are loaded into the worker.
4

Execute function

The appropriate function (onRequest, onResponse, or onTest) is called.
5

Extract changes

Changes to the request or environment are extracted from the worker.
6

Terminate worker

The worker is terminated after execution completes or times out.

Error handling

Script errors are captured and returned in the execution result:
const result = await entity.executePreRequestScript(context);

if (result.success) {
  console.log('Script executed successfully');
  console.log('Updated context:', result.context);
} else {
  console.error('Script error:', result.error);
  console.error('Stack trace:', result.error.stack);
}

Best practices

Keep scripts focused: Each script should have a single, clear purpose. Avoid complex logic that’s hard to debug.
Use environment variables: Don’t hardcode values in scripts. Store configuration in environment variables.
Log strategically: Use console.log() to debug scripts, but remove excessive logging in production.
Handle errors gracefully: Use try-catch blocks for operations that might fail, like JSON parsing.
Scripts have a 30-second execution timeout. Ensure your scripts complete quickly to avoid timeout errors.

Performance considerations

Worker pooling

Tanxium reuses workers when possible to improve performance.

Heartbeat monitoring

Workers send heartbeat signals to detect frozen scripts.

Automatic cleanup

Workers are automatically terminated after execution.

Timeout protection

Scripts that exceed 30 seconds are automatically terminated.

Next steps

REST API Testing

Use scripts in REST requests

Environments

Manage variables accessed by scripts

Schema Language

Learn about script block syntax

Workspaces

Understand workspace structure

Build docs developers (and LLMs) love