Pre-request scripts and tests in .http files
Plainwire 0.13 runs JavaScript written in .http files, in the JetBrains HTTP Client format. A < {% … %} block above a request is a pre-request script: it can compute a signature or a timestamp before the request is sent. A > {% … %} block after a request is a response handler: it can save a token for later requests and run tests with client.test. The same files run in IntelliJ IDEA and WebStorm, in VS Code, Cursor and VSCodium, and in CI with the free plainwire CLI.
Postman collections you import keep their scripts too: Plainwire runs them with a Postman-compatible pm API (details below). REST Client, the most-installed .http extension, does not run scripts; issue #521 asks for it.
Log in once, reuse the token
The response handler runs after the response arrives. response.body is the parsed JSON (or the text, when the body is not JSON), and client.global.set stores a value that later requests use as {{name}}:
### Log in POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "ada", "password": "{{password}}"} > {% client.test('logged in', () => { client.assert(response.status === 200, 'status ' + response.status); client.assert(response.body.token, 'no token in the response'); }); client.global.set('token', response.body.token); %} ### Who am I # @assert $.name == "ada" GET {{baseUrl}}/me Authorization: Bearer {{token}}
Send Log in once; every later request in the workspace can use {{token}} until you clear it. In the extension, client.global values are kept per workspace (they survive a reload). In the CLI they last for one run. If you send Who am I before anything has set token, the error names the request whose handler sets it and asks you to send that one first, or to use Run all.
For a single value from one response, request chaining ({{login.response.body.$.token}}) needs no script and sends login for you when needed. A script is useful when you want to check the response first, combine values, or share one token across many files.
Sign a request before it is sent
A pre-request script runs before the request’s {{variables}} are filled in. request.variables.set(name, value) sets a variable for this request only. This example signs the body with HMAC-SHA256 and a secret from the environment:
### Create an order (signed) < {% const ts = Math.floor(Date.now() / 1000).toString(); const signature = crypto.hmac.sha256() .withTextSecret(request.environment.get('apiSecret')) .updateWithText(ts + '\n' + request.body.tryGetSubstituted()) .digest().toHex(); request.variables.set('ts', ts); request.variables.set('signature', signature); %} POST {{baseUrl}}/orders Content-Type: application/json X-Timestamp: {{ts}} X-Signature: {{signature}} {"item": "book", "qty": 1}
request.environment.get reads the active environment, including values from http-client.private.env.json. tryGetSubstituted() returns the text with the variables it can resolve filled in; getRaw() returns it as written. If a pre-request script throws or times out, the request is not sent: you see “Not sent: the pre-request script: …” with the script’s log.
Tests with client.test
client.test(name, fn) records a passed check when fn returns and a failed one when it throws, for example through client.assert(condition, message). These results appear next to your # @assert checks: in the response’s Tests tab, in the Run all report, and in the CLI’s output and JUnit, JSON and Markdown reports and GitHub annotations. A request passes when all its checks of both kinds pass.
### List orders # @assert status == 200 GET {{baseUrl}}/orders Authorization: Bearer {{token}} > {% client.test('every order has an id', () => { for (const order of response.body.items) { client.assert(order.id, 'order without an id: ' + JSON.stringify(order)); } }); client.test('JSON response', () => { client.assert(response.contentType.mimeType === 'application/json', response.contentType.mimeType); }); client.log('orders:', response.body.items.length, 'first id:', jsonPath(response.body, '$.items[0].id')); %}
A client.assert outside any client.test, or an uncaught error, ends the handler and counts as one failed check. client.exit() ends a script early without failing it. client.log and console.log lines appear under “Script log” in the response’s Tests tab (a Log tab when the request has no checks).
Streams: server-sent events and WebSocket
For a server-sent events or WebSocket request, the handler runs once the stream has ended, and response.body.onEachMessage replays the messages that were received (JSON messages are parsed; for WebSocket, only the server’s messages):
> {%
const types = [];
response.body.onEachMessage((message, unsubscribe) => {
types.push(message.type);
if (message.type === 'done') unsubscribe();
});
client.test('got a pong', () => client.assert(types.includes('pong'), 'got ' + types.join(', ')));
%}
response.body.onEachLine does the same line by line.
What a script can use
| Name | What it does |
|---|---|
request.variables.set(name, value), .get(name) | A variable for this request only. Set it in a pre-request script. |
request.environment.get(name) | A value from the active environment, or null. |
request.method, request.url, request.headers, request.body | url.tryGetSubstituted(), headers.findByName(name).tryGetSubstitutedValue(), headers.all(), body.getRaw(), body.tryGetSubstituted(). |
response.status, response.body | Response handlers only. The body is parsed JSON, the text, or a stream (above). |
response.headers.valueOf(name), .valuesOf(name) | The first value of a header (or null), or all its values. |
response.contentType.mimeType, .charset | From the Content-Type header, e.g. application/json. |
client.test(name, fn), client.assert(cond, msg) | Checks, reported with # @assert results. |
client.global.set/get/clear/clearAll/isEmpty | Values kept between requests and used as {{name}}. Stored as strings; objects are stored as JSON. |
client.log(…), console.log(…), client.exit() | Write to the script log; stop the script. |
crypto.sha256().updateWithText(s).digest().toHex() | Also md5, sha1, sha384, sha512; crypto.hmac.sha256().withTextSecret(key) (or withHexSecret, withBase64Secret); .toBase64(), .toUrlSafeBase64(). |
$random.uuid, $random.integer(from, to) | Also alphabetic(n), alphanumeric(n), hexadecimal(n), float(from, to), email. |
jsonPath(obj, '$.a.b'), btoa, atob | A JSONPath lookup (or null); Base64 encode and decode. |
Code can also live in a file next to the .http file: < ./sign.js above the request line, > ./check-order.js after the request. A request can have several scripts on each side; they run in file order, and the first one that fails stops the rest.
Which value a {{variable}} gets
request.variables.setfrom this request’s pre-request script- File variables (
@name = value) - The active environment (
http-client.env.jsonand the private file) client.global
So a value saved with client.global.set('token', …) is not used while your environment or file also defines token, even as an empty string. Remove that entry, or use a different name.
In the editor
- The request editor has a Scripts tab with a box for the pre-request script and one for the response handler; Plainwire writes them to the file as
< {% %}and> {% %}blocks. Script files the request uses are named above the boxes. - Plainwire: Show / Clear Script Variables (client.global)… lists the stored values and clears one or all of them.
- The setting
plainwire.runScripts(on by default) turns scripts off; they stay in the file and are skipped.
Postman scripts
When you import a Postman collection, a test script made only of common checks still becomes # @assert lines. Any other test script (one that sets variables, or has conditions or loops) and every pre-request script is kept whole as a > {% %} or < {% %} block:
### Create user < {% pm.variables.set("requestId", "req-" + Date.now()); %} POST {{baseUrl}}/users X-Request-Id: {{requestId}} Content-Type: application/json {"name":"Ada"} > {% pm.test("created", function () { pm.response.to.have.status(201); var body = pm.response.json(); pm.expect(body).to.have.property("id"); pm.expect(body.name).to.be.a("string").and.not.empty; pm.environment.set("userId", body.id); }); tests["fast enough"] = responseTime < 2000; %}
Plainwire runs these blocks with its own implementation of the pm API. What works:
pm.test, andpm.expectwith the common assertion chain:equal,eql,include,a/an,above,below,least,most,within,lengthOf,match,oneOf,property,keys,members;ok,true,false,null,undefined,exist,empty;notanddeep. It is not all of Chai.pm.response:code,status,responseTime,json(),text(),headers.get, andpm.response.to.have.status/header/body/jsonBody,to.be.ok/success/error/json.pm.environment,pm.collectionVariablesandpm.globals:setwrites toclient.global, so later requests use the value as{{name}}.pm.variables.setin a pre-request script applies to that request only.getreads request variables, thenclient.global, then the environment.- The legacy forms:
tests["name"] = condition,postman.setEnvironmentVariable,responseBody,responseCode.
Not supported: pm.sendRequest (put that request in the .http file and chain it with # @name), require(), pm.visualizer, pm.cookies, pm.vault, and async tests. The importer prints a warning for a script that uses pm.sendRequest, require(), pm.visualizer, pm.cookies, pm.execution or pm.vault. Scripts on a Postman folder or on the whole collection are not imported and are listed as warnings. Thunder Client scripts are not imported.
In CI
The free plainwire CLI runs scripts the same way:
$ plainwire run api/ --env staging --junit results.xml # scripts run $ plainwire run api/ --no-scripts # skip every < {% %} and > {% %} $ plainwire run api/ -v # also print every script's log
For a failed request the CLI always prints that request’s script log. Running the examples on this page against a local test server, with the CLI built from the 0.13 source on 20 November 2026, printed:
✓ POST Log in 200 · 23 ms · 1/1 checks
✓ GET Who am I 200 · 4 ms · 1/1 checks
✓ POST Create an order (signed) 201 · 3 ms · 1/1 checks
✓ GET List orders 200 · 2 ms · 3/3 checks
log orders: 2 first id: 1
✓ GET Events 200 · 3 ms · 3 events (closed) · 1/1 checks
Safety
Scripts run in a separate Node.js vm context with a 5 second time limit. That context keeps scripts from changing Plainwire by accident; it is not a security sandbox, and a script can reach the rest of Node.js. Treat scripts in .http files like any other code in your repository: review them in pull requests, and do not run files you have not read.
- In VS Code, scripts run only in trusted workspaces. In Restricted Mode, VS Code does not enable Plainwire at all.
- The CLI runs scripts by default. Use
--no-scriptswhen a pipeline runs files from people you do not trust, such as pull requests from forks. - Set
plainwire.runScriptstofalseto keep scripts in the files but never run them in the editor.
Limits
- Scripts run synchronously. There is no
fetch,requireor timer, and work left in a Promise when the script returns is not waited for. - A script cannot send another request. Put it in the file and use
# @namechaining or Run all. - httpYac’s
{{ … }}script blocks and?? jslines with arbitrary JavaScript are not run;?? jswith a simple path works (details). client.globalandrequest.variablesvalues are strings.
FAQ
Does it work in Cursor, Windsurf and VSCodium?
Yes, it is the same extension. Install the .vsix from the latest release; see installing in Cursor and VSCodium.
Do I need scripts for tests?
No. Most checks fit on one # @assert line, such as status == 200 or $.id exists. Use client.test when a check needs a loop, a condition or a computed value.
Is anything sent to Plainwire?
No. There is no account and no telemetry. The extension makes no network requests except the ones you send, and the source is on GitHub (MIT).