Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 30 ยท Writing Tests and Scripts

Pre-request scripts

Write Postman pre-request scripts with the pm API: set variables, add timestamps and dynamic data, sign requests with HMAC, and use the built-in libraries.

So far every value in your requests was either typed by hand or stored in a variable you set yourself. Real APIs often need values that cannot be typed in advance: a timestamp that must be fresh, a random email for a new user, a request signature computed from the body, a token that expires every hour. A pre-request script is a piece of JavaScript that Postman runs just before sending a request, so it can compute those values and put them into variables, headers or the body.

This lesson introduces the pm object, the common pre-request jobs, signing with HMAC, and the libraries built into Postman's script sandbox. The real sandbox lives inside Postman, so the Postman-only code is shown read-only. You can still run stand-ins: a small imitation of the pm object in plain JavaScript, and a real HMAC signature in Node.

What runs when

Pre-request script Runs before the request is sent.
Request Variables are resolved, then it is sent.
Tests Run after the response arrives.

Order: collection, folder, request for scripts at every level.

1 / 2

Where to write a script

Open a request, a folder or a collection and choose the Scripts tab (called Pre-request Script in some versions). Write JavaScript there. Scripts at every level run in order: collection first, then folder, then the request, so shared preparation belongs high in the tree (see Collections, folders and requests). Anything you print with console.log shows up in the Postman Console, which is your main debugging tool.

The pm object

Every script receives a global object named pm. These are the parts you will use most:

JavaScript
// Variables, by scope (see the Environments lesson)
pm.environment.set("orderId", "1001");
pm.environment.get("orderId");
pm.collectionVariables.set("version", "v1");
pm.globals.set("team", "qa");
pm.variables.set("temp", "x");        // local: this request only
pm.variables.get("orderId");          // resolves through all scopes

// Resolve {{placeholders}} in a string, including dynamic ones
const email = pm.variables.replaceIn("user-{{$guid}}@example.com");

// The request that is about to be sent
pm.request.headers.add({ key: "X-Request-Time", value: String(Date.now()) });
pm.request.method;                    // "POST"
pm.request.url.toString();

// Information about the run
pm.info.requestName;
pm.info.iteration;

Variables are covered in Environments and variables. One rule worth repeating: setting a variable in a pre-request script changes the current value only, and a new value is picked up when this request is built, so you can use it in the URL, headers and body of the same request.

Names and details of the pm API evolve between Postman versions, so check the Postman documentation for the exact version you use when something does not behave as shown here.

Timestamps and dynamic data

A signed API often rejects requests whose timestamp is too old, and a sign-up endpoint rejects an email that already exists. Both are solved with a few lines:

JavaScript
pm.variables.set("timestamp", Math.floor(Date.now() / 1000));
pm.variables.set("uniqueEmail", `user-${Date.now()}@example.com`);
pm.variables.set("orderRef", "ORD-" + Math.floor(Math.random() * 1e6));

Then the request body uses {"email": "{{uniqueEmail}}"}. Postman also has built-in dynamic variables such as {{$guid}}, {{$timestamp}} and {{$randomInt}}, which need no script at all. Scripts are better when you need the same generated value in several places (header and body) or when the value depends on a calculation.

Time-based code cannot give a repeatable output, which matters for tests. The stand-in below makes the idea visible by taking the "clock" as a parameter, so the result is deterministic.

A mini pm object

You cannot run Postman's sandbox here, but the logic of a pre-request script is simple enough to imitate. This stand-in builds a tiny pm with variable storage, replaceIn and a request with headers, then runs a script against it.

JS A mini pm object running a pre-request script

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The final object is what would actually be sent: the placeholders in the URL, header and body were all resolved from values the script computed.

Signing requests with HMAC

Some APIs prove that a request was not tampered with by requiring a signature: the client computes an HMAC (a keyed hash) of selected request parts with a secret key, and sends it in a header. The server repeats the computation and compares. A typical recipe is to sign the method, path, timestamp and body, joined with newlines.

In a Postman pre-request script the built-in CryptoJS library does the hashing. This code is read-only here, and the exact message layout is whatever your API specifies:

JavaScript
const secret = pm.environment.get("apiSecret");
const timestamp = Math.floor(Date.now() / 1000).toString();
const body = pm.request.body ? pm.request.body.raw : "";
const message = [pm.request.method, "/orders", timestamp, body].join("\n");

const signature = CryptoJS.HmacSHA256(message, secret).toString(CryptoJS.enc.Hex);

pm.request.headers.add({ key: "X-Timestamp", value: timestamp });
pm.request.headers.add({ key: "X-Signature", value: signature });

The same computation can run for real on Piston with Node's crypto module. The stand-in signs with a fixed timestamp so the output never changes, then plays the server: it recomputes the signature and shows that a changed body no longer verifies.

Node.js Sign and verify a request with HMAC-SHA256

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two real-world warnings. First, keep the secret in a variable of type secret, never in the script text. Second, both sides must build the message byte for byte the same way, so whitespace in the body matters: sign the exact text that is sent.

Built-in libraries

The Postman script sandbox includes several libraries you can use without installing anything. Commonly available ones include CryptoJS (hashes, HMAC, AES), lodash as _, moment, uuid, cheerio, ajv and chai, and you can load a bundled module with require:

JavaScript
const uuid = require("uuid");
const id = uuid.v4();
pm.variables.set("requestId", id);

const total = _.sumBy(items, "price");

The list of available modules changes over time, so confirm in the Postman documentation, and do not expect arbitrary npm packages: you cannot require("axios").

Sending a helper request

Sometimes the value you need comes from another call, for example a fresh access token. pm.sendRequest sends a request from inside the script and gives you the response in a callback. This pattern is read-only here and appears again in Chaining requests and workflows:

JavaScript
const tokenRequest = {
  url: pm.environment.get("baseUrl") + "/auth/token",
  method: "POST",
  header: { "Content-Type": "application/json" },
  body: { mode: "raw", raw: JSON.stringify({ user: "demo", password: "s3cret" }) },
};

pm.sendRequest(tokenRequest, (error, response) => {
  if (error) { console.error(error); return; }
  pm.environment.set("token", response.json().access_token);
});

Debugging tips

  • console.log everything while developing, then open the Console (bottom bar).
  • A syntax error stops the request, and the Console shows the line.
  • Remember that setting a variable after the request is built has no effect on that request.
  • Keep scripts short; put shared logic at the collection level.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a pre-request script run?

    Pre-request scripts run before sending; test scripts run after the response.
  2. 2. In which order do scripts at different levels run before a request?

    Scripts run from the outermost level inward, which is why shared setup belongs at the collection level.
  3. 3. Why does an HMAC signature stop verifying if the body is changed after signing?

    The hash covers the body, so any change produces a different value. That is the point of signing.
  4. 4. Where should the HMAC secret be stored?

    Scripts are shared and exported with collections, so secrets belong in variables kept out of shared data.
  5. 5. You set a variable with pm.variables.set in a pre-request script. Where can you use it?

    The variable is set before the request is built, so {{placeholders}} in that request resolve to the new value.

Summary

  • A pre-request script is JavaScript that runs before the request is sent; collection, folder, then request.
  • The pm object sets and reads variables, resolves placeholders and edits the outgoing request.
  • Timestamps, unique data and signatures are the classic uses; keep secrets in variables.
  • HMAC signing hashes a defined message with a secret; verify that both sides build the message identically.
  • Built-in libraries such as CryptoJS, lodash and uuid are available, but not arbitrary npm packages.
  • Use the Console to debug.

Next: check what comes back with Writing tests with pm.test and Chai.