Skip to main content

Scripting ›Overview

Изменить на GitHub

Эта документация доступна на английском языке.

Scripting Overview

Scripts are small pieces of JavaScript that run around a request:

  • A Pre-Request script runs before the request is sent. It can change the URL, params, headers, and body, add a timestamp or signature, or set variables.
  • A Post-Response script runs after the response arrives. It can read the response, run tests, and save values, such as a token, for the next request.

Open the Scripts tab in the Request Builder. It has one editor for each script. A dot on the tab (Scripts ●) means at least one script isn't empty.

A first example

Add a request ID header to every call, then check the response.

Pre-Request

JS
dotfetch.request.headers['X-Request-Id'] = dotfetch.crypto.uuid();

Post-Response

JS
test('Status is 200', () => {
  assert(dotfetch.response.status === 200, `Expected 200, got ${dotfetch.response.status}`);
});

Send it to https://httpbin.org/headers. The response shows your X-Request-Id, and the Tests tab in the response shows ✓ 1.

The order things happen in

CODE
 1. Build the request from the URL bar, Params, Headers, and Body
        {{VARIABLES}} are NOT filled in yet
 2. Run the Pre-Request script        ← can change the request and set variables
 3. Fill in {{VARIABLES}}             ← includes variables set in step 2
 4. Apply the Auth tab                ← always wins over Authorization from steps 1–2
 5. Send the request
 6. Run the Post-Response script      ← can read the response, run tests, set variables
 7. Show the response and test results

Three consequences you'll use often:

  1. Pre-Request scripts see {{VARIABLES}} unfilled. If the body is {"user":"{{USER_ID}}"}, then dotfetch.request.body is that exact text. Call dotfetch.env.resolve() to get the value that will actually be sent.
  2. A variable set in the Pre-Request script is used by the same request. Set TS in the script and write {{TS}} in a header, and the header gets the new value.
  3. The Auth tab is applied after your script. To build Authorization yourself, set Auth to No Auth (details).

What's available in a script

NamePre-RequestPost-ResponsePage
dotfetch.env✅✅Environment
dotfetch.request✅ read & write—Request & Response
dotfetch.response—✅ read onlyRequest & Response
test(name, fn)—✅Tests
assert(condition, message)✅✅Tests
dotfetch.crypto✅✅Crypto & Utils
dotfetch.utils✅✅Crypto & Utils
console.log / warn / error✅✅below

Standard JavaScript is available too: JSON, Math, Date, Array, Object, String, RegExp, parseInt, and the rest.

Not available: require, import, fetch, setTimeout, file access, or process. A script can't make its own HTTP calls. To chain requests, save a value in one request's Post-Response script and use it as {{VARIABLE}} in the next request (example).

Rules

  • Scripts are synchronous. async / await and Promises won't wait for anything. An async test callback is reported as a failed test.
  • 5-second limit. A script that runs longer (an endless loop, say) is stopped and counts as failed.
  • Values are strings. dotfetch.env.set('N', 5) stores "5", and headers and params hold strings too.

When a script fails

A script fails when it throws an error, an assert() outside a test() fails, it has a syntax error, or it hits the 5-second limit.

Pre-Request failsPost-Response fails
Is the request sent?No. It fails closed: a broken signature or missing token never reaches the server.Yes, it was already sent
What you seeStatus Error, and the body shows ⚠️ Pre-request script failed (line 3): <message>The normal response, plus a ⚠️ Post-Response Script Error (Line N) card in the Tests tab
Variables set by the scriptDiscardedDiscarded
Tests—Tests that finished before the error are still shown
History🔴 FailedShows the HTTP status

Example: the line number points at your script.

JS
const body = JSON.parse(dotfetch.request.body);   // line 1
assert(body.amount > 0, 'amount must be positive'); // line 2 ← fails
⚠️ Pre-request script failed (line 2): amount must be positive

Logging

console.log, console.warn, and console.error write to VS Code's Output panel. Choose DotFetch in its dropdown:

JS
console.log('user', dotfetch.response.json().id, { ok: true });
[Script] user 42 { ok: true }

Objects are printed up to 4 levels deep.

Security

Scripts run with the same trust as code in your project: DotFetch treats them as your code. The script environment limits what scripts can reach, but it isn't a security sandbox against hostile code.

  • Read any script you didn't write (from a shared collection, a colleague, the internet) before pressing Send.
  • Scripts are saved with requests in Collections, but never in History.
  • Prefer dotfetch.env.get('SECRET') over pasting secrets into the script text.
Overview · DotFetch Docs | dotsuite