Creating a custom code generator
Write a JavaScript generator that turns requests into code in the form you need.
Overview
Every format in the Preview panel comes from a generator: a JavaScript file with a manifest that names it and a generate function that turns a request into text. Relay's own generators work the same way as the ones you write, so you can add a client library Relay doesn't cover, match your team's coding style or change how a built-in generator writes its code.
Generators run in a sandbox with no network or file access, and Relay runs them each time the Preview panel needs code. For the full API, see Code Generator API.
Create a generator
-
Choose Relay > Settings, then click Exporters.
The list shows the HTTP and WebSocket generators in separate sections. Generators you've written are marked Custom.
-
Click the Add button (+) at the bottom of the list, then choose New HTTP Generator or New WebSocket Generator.
Relay creates a generator from a template and opens its source in the editor.
-
Edit the
manifestand thegeneratefunction. -
Click Save, or press Command-S. To discard your changes instead, click Revert.
-
In the request editor, open the Preview panel and choose your generator from the format menu. It appears under the
groupits manifest names.
The HTTP template lists the request's method, URL and headers:
var manifest = {
id: 'my-generator',
name: 'My Generator',
group: 'Custom',
language: 'plaintext',
fileExtension: 'txt',
order: 1000
};
// `req` is the resolved request; `r` is Relay's helper namespace.
// Duplicate a built-in generator to see the full API in use.
function generate(req, r) {
var b = r.builder('\n');
b.add(req.method + ' ' + req.url);
for (var i = 0; i < req.headers.length; i++) {
b.add(req.headers[i].name + ': ' + req.headers[i].value);
}
return b.join();
}The WebSocket template has kind: 'websocket' in its manifest and also lists the request's saved messages. A generator only appears for requests of its kind.
Write the generator
A generator's file has two parts:
- The manifest: A top-level
manifestobject. Itsididentifies the generator,nameis what the format menu shows, andgroupis the heading it's listed under.languagechooses the syntax highlighting,fileExtensionis used when you save the code, andordersorts it within its group. For every field, see manifest. - The generate function: A top-level
function generate(req, r)that returns the code as a string.reqis the request, with variables and inherited authentication already applied, andrholds helpers for quoting, encoding and headers. For details, see generate, ExportRequest and relay.
Text you pass to console.log, console.warn or console.error appears above the code in the Preview panel, each line starting with //. Use it to check values while you work, or to tell people about something the code can't express.
Build an example generator
This generator writes a request as a file for the HTTP Client in JetBrains IDEs. It writes the method and URL, every header Relay would send, including those for authentication and cookies, and the body. A multipart file field points at the file's path, which the HTTP Client reads when it sends.
var manifest = {
id: 'jetbrains-http',
name: 'HTTP Client',
group: 'JetBrains',
language: 'http',
fileExtension: 'http',
order: 200
};
function generate(req, r) {
var out = r.builder('\n');
out.add('### ' + (req.name || 'Request'));
// A comment for auth the file can't carry, such as Digest or an expiring signature.
var note = r.authNote(req.auth, req);
if (note) out.add('# ' + note);
if (req.settings && !req.settings.followsRedirects) out.add('# @no-redirect');
out.add(req.method + ' ' + req.url);
// The request's headers plus the ones Relay adds for auth and cookies.
var headers = r.allHeaders(req);
for (var i = 0; i < headers.length; i++) {
out.add(headers[i].name + ': ' + headers[i].value);
}
var body = bodyText(req);
if (body !== null) {
out.add('');
out.add(body);
}
if (req.meta.missingVariables.length > 0) {
console.warn('Undefined variables: ' + req.meta.missingVariables.join(', '));
}
return out.join();
}
function bodyText(req) {
if (req.body.type === 'none') return null;
if (req.body.type !== 'multipart') return req.body.text;
// The HTTP Client reads a file part's contents from the path after `<`.
var lines = [];
var parts = req.body.parts;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
lines.push('--' + req.body.boundary);
if (part.isFile) {
lines.push('Content-Disposition: form-data; name="' + part.name + '"; filename="' + (part.fileName || '') + '"');
lines.push('Content-Type: ' + part.contentType);
lines.push('');
lines.push('< ' + part.value);
} else {
lines.push('Content-Disposition: form-data; name="' + part.name + '"');
lines.push('');
lines.push(part.value);
}
}
lines.push('--' + req.body.boundary + '--');
return lines.join('\n');
}For a JSON POST request named Create item, with bearer token authentication and a cookie, it writes:
### Create item
POST https://api.example.com/items?draft=true
Accept: application/json
User-Agent: Relay
Content-Type: application/json
Authorization: Bearer abc123
Cookie: session=xyz
{
"name": "Widget"
}Because the multipart Content-Type header Relay provides already names req.body.boundary, the parts and the header agree. A generator for a library that builds multipart bodies itself would remove that header with r.headersWithout(headers, ['Content-Type']) instead.
Start from a built-in generator
The quickest way to write a generator for a library Relay already supports is to copy one of Relay's.
- In the Exporters pane, select a built-in generator.
- Click Duplicate Generator at the bottom of the list, or Control-click the generator and choose Duplicate.
The copy is a custom generator named after the original with Copy at the end, with its own id, so both appear in the format menu.
Change a built-in generator
You can edit a built-in generator directly. When you save it, Relay saves your version as a custom generator with the same id, and your version replaces the built-in one everywhere, including the Preview panel and the MCP server. To go back to Relay's version, delete yours.
Delete a generator
Select a custom generator and click Delete Generator (−) at the bottom of the list, or Control-click it and choose Delete. If it replaced a built-in generator, the built-in one comes back. You can't delete Relay's own generators.
Share generators
Each custom generator is a .js file in Relay's generators folder, named after its id. To open the folder, click Reveal in Finder at the bottom of the list. To share a generator, send someone its file. To add one, put its file in the folder and reopen Relay.
Keep a generator's id once you've created it. To make a variant with a new id, duplicate the generator instead.
Fix a generator
When a generator throws an error or returns something other than a string, the Preview panel shows the error and its line number instead of code. A generator that runs for more than two seconds is stopped, and Relay doesn't run it again until you change it.
Relay leaves a generator out of the list and the format menu when it can't load it: when the file has a syntax error, or its manifest is missing, has no name or names a kind other than http or websocket. Click Reveal in Finder, fix the file in a text editor, and reopen Relay.
Create a generator from an AI agent
An AI agent connected to Relay's MCP server can write a generator for you. It reads a built-in generator with the get_generator tool, tries its own with test_generator, which saves nothing, and saves the finished one with create_generator. For a list of tools, see MCP Tools.
See Also
- Code Generator API: The manifest, request model and helpers for writing code generators.
- Generating code from requests: Turn a request into code for curl, Python, JavaScript, Swift and other languages.
- Configuring Relay settings: Change Relay's defaults for requests, networking, history, code export and the MCP server.