postmanpostman-pre-request-script

Execute pre-request script after request variable resolution


I am writing a pre-request script that uses a particular type of authentication for the third-party endpoint I'm trying to request. The third-party endpoint's authentication uses a 'Signature' header which is an encrypted and base64'd version of the entire request body.

Due to the way that the pre-request scripts execute in Postman, it means it creates the Signature header before resolving any variables used in the request body. This makes the Signature incorrect, as it contains "{{Variable Name}}" instead of the actual resolved variable.

If I manually resolve those variables and paste the values directly into the request body, the Signature header is assembled correctly and the authentication succeeds, however, if my request body uses any variables, it fails.

What I would ideally like to do is find a way to either:

  1. Force Postman to resolve variables before executing the pre-request script; or
  2. Defer the authentication pre-request script until just before the request is sent.

Is this possible?


Solution

  • There’s no way to reorder Postman’s execution pipeline (scripts will always run before variable substitution in the request body).

    You also cannot defer the pre-request script “until just before send.”.

    You can use pm.variables.replaceIn(). Postman exposes an API that lets you manually resolve variables in scripts the same way it would in the request body:

    let rawBody = `
    {
      "username": "{{user}}",
      "password": "{{pass}}"
    }
    `;
    
    // Replace {{...}} with actual values
    let resolvedBody = pm.variables.replaceIn(rawBody);
    
    // Now use resolvedBody to generate the signature
    let signature = CryptoJS.HmacSHA256(resolvedBody, pm.environment.get("secretKey"));
    let encoded = CryptoJS.enc.Base64.stringify(signature);
    
    pm.request.headers.add({
      key: "Signature",
      value: encoded
    });
    

    That way you’re explicitly telling Postman to resolve the variables first.

    Also see: https://learning.postman.com/docs/tests-and-scripts/write-scripts/variables-list/