Running scripts before and after requests
Add pre-request and post-response scripts to requests, folders and collections.
Overview
A script is JavaScript that runs each time you send a request. A pre-request script runs before Relay sends the request: it can set variables, change the request's headers, URL or body, fetch data from another endpoint, or skip the request. A post-response script runs after the response arrives: it can test the response, save values from it for later requests and log what it finds.
Requests, folders and collections each have both kinds of script. A script on a collection or folder runs for every request inside it, which makes it a good place for work that many requests share, such as signing requests or checking that every response is JSON.
Scripts use the Scripting API: the relay object, also available as pm, along with test, expect and a set of bundled libraries.
Add a script to a request
- Select the request in the sidebar.
- In the request editor, click Scripts, or press Command-6.
- Click the phase menu at the top of the tab and choose Before Request or After Response. A dot marks each phase that already has a script.
- Enter your script.
A pre-request script that adds a header with a fresh ID:
relay.request.headers.upsert({ key: "X-Request-Id", value: crypto.randomUUID() });A post-response script that tests the response and saves a value from it:
test("Status is 200", () => {
relay.response.to.have.status(200);
});
relay.environment.set("userId", relay.response.json().id);To start from a ready-made script, click Snippets and choose one, such as Status code is 200, Save a value to the environment or Fetch a token first. Relay inserts it at the insertion point. The menu lists the snippets for the phase you're editing.
Use completions and syntax checking
As you type a name, or a period after one, the editor suggests the functions and properties that fit, with a short description of the selected one. Press Return or Tab to accept a suggestion, or press Option-Escape to show suggestions at any time. Suggestions include only what works in the phase you're editing, so relay.response isn't suggested in a Before Request script.
When you pause typing, the editor underlines a syntax error and marks its line in the gutter. Hold the pointer over the underline or the mark to read the error.
Add scripts to a collection or folder
- In the sidebar, Control-click a collection or folder and choose Edit Scripts….
- In the Collection Settings window, choose a phase and enter the script.
A collection's or folder's script runs for every request inside it, including requests in its subfolders. For more about what collections and folders can share with their requests, see Configuring collections and folders.
Understand the order scripts run in
In both phases, scripts run from the outside in: the collection's script first, then each folder's from the outermost to the innermost, then the request's. Each script finishes before the next one starts, including any timers, tests and requests it's waiting for.
Drafts don't belong to a collection, so a draft runs only its own scripts.
When a collection or folder above a request has a script for the phase you're editing, the Scripts tab shows a button such as Also runs 2 scripts. Click it to see every script in the phase, numbered in the order they run, with the request's own script last. Each row has a menu with these commands:
- Copy Script: Copies the script's text.
- Disable Scripts or Enable Scripts: Turns that level's scripts off or on.
- Edit Script…: Opens the collection's or folder's scripts in the Collection Settings window.
The path at the bottom of the popover opens the scripts of any level above the request.
Turn scripts off
To stop a request's, folder's or collection's scripts from running without deleting them, turn off Enabled at the top of its Scripts tab. The switch covers both phases. When every level above a request has its scripts turned off, the request's button reads Inherited scripts off.
The Enabled switch is saved with the request, folder or collection, so it's shared with anyone who uses the workspace's files. You can undo it like any other change.
Understand what happens when you send
When you send a request that has scripts, Relay works through these steps:
- Runs the pre-request scripts. They see the request as you wrote it, with its
{{name}}tokens not yet replaced. - Saves the variables the scripts set, and applies the changes they made to the request for this send. The request in the editor doesn't change.
- Resolves the request's variables, applies its authentication and gets an OAuth 2.0 token if it needs one.
- Sends the request.
- Runs the post-response scripts with the response, and saves the variables they set. If the request failed without a response, such as when the server couldn't be reached, they don't run.
- Records the response in history, with the test results and console output in its Tests tab.
Both phases of a send share one JavaScript environment, and each send starts with a fresh one. Each script runs inside an async function, so you can use await at the top level, and the let and const declarations in one script don't clash with another's. To pass a value from a pre-request script to a post-response script, or to the request itself, use relay.variables.set(). See Reading and writing variables in scripts.
Handle errors and timeouts
When a pre-request script throws an error or runs out of time, the scripts after it don't run and Relay doesn't send the request. It records the attempt in history as a failed response, and the response inspector's Tests tab shows the error. A script can also stop the request deliberately with relay.execution.skipRequest().
When a post-response script fails, Relay keeps the response and runs the remaining post-response scripts. The error appears in the Tests tab, with a link that shows the line where it happened.
Each phase must finish within the Script Timeout set in Relay > Settings > Requests, 30 seconds by default. The time includes timers and requests the scripts are waiting for.
Important
while (true) {}. When a script like that runs past the timeout, Relay stops waiting for it and pauses it until you edit it. If several scripts get stuck this way, Relay stops running scripts until you restart it.Know where scripts don't run
- Previews and code: The Preview panel and the code Relay generates from a request don't run scripts, so they don't include changes or variables a pre-request script would make.
- GraphQL schemas: Fetching a GraphQL schema doesn't run the request's scripts.
- WebSocket requests: A WebSocket request has one script, labeled Before Connecting, which runs before Relay opens the connection and can set variables and change the handshake's headers. Its collection's and folders' pre-request scripts run before it. No script runs after a WebSocket connection.
- Scripts that changed outside Relay: A script that arrived through a Git pull, an import or an AI agent doesn't run until you allow it. See Allowing scripts to run.
See Also
- Testing responses: Check responses automatically with tests and assertions.
- Reading and writing variables in scripts: Read variables and set new values from pre-request and post-response scripts.
- Allowing scripts to run: Review and allow scripts that changed outside Relay before they run.
- Scripting API: The objects and functions available to request scripts.