Automating API Tests with Hoppscotch’s Pre‑Request and Post‑Response Scripts
Learn how Hoppscotch's JavaScript sandbox handles pre‑request token fetching and post‑response assertions, where the 5‑second timeout and callback‑only async model fit, and a ready‑to‑paste example you can run today.
04 Sept 2025, 07:16 UTC

The problem: dynamic auth and validation without leaving the client
When you test an API that requires a short‑lived token, you normally write a separate script to fetch the token, copy it into a header, and then assert the response shape. Doing that outside the API client adds friction and makes the test suite harder to share. Hoppscotch solves part of this by embedding a JavaScript sandbox that runs before a request is sent and after a response arrives.
What the sandbox actually gives you
The sandbox exposes a pm object that mirrors the Postman scripting API. The most useful members are:
pm.variables,pm.environment,pm.collectionVariables– read/write variables at three scopes.pm.sendRequest(request, callback)– fire an auxiliary HTTP call (async, callback‑style).pm.test(name, fn)– register assertions that appear in the test results panel.- Dynamic variables like
$randomInt,$timestamp,$uuid,$isoTimestampare resolved before your script runs and can be read viapm.variables.get().
Scripts execute in an isolated context per request with a hard 5‑second timeout. Only ES2020 syntax is supported; top‑level await is not allowed, so asynchronous work must stay inside the pm.sendRequest callback or a Promise chain.
Variable persistence: session vs. collection runner
In the web app, any variable you write with pm.environment.set() or pm.variables.set() lives only for the current browser session. When you run a collection via the CLI or the built‑in collection runner, those writes can be persisted to the collection file if you enable the “persist variables” option. This difference matters when you design a flow that expects a token to survive across multiple requests.
Worked example: token refresh + response validation
Below is a minimal, self‑contained flow you can paste into Hoppscotch’s UI to see the sandbox in action.
1. Pre‑request script (fetch token)
// Pre‑request script
const authUrl = pm.environment.get('authUrl') || 'https://api.example.com/oauth/token';
const clientId = pm.environment.get('clientId');
const clientSecret = pm.environment.get('clientSecret');
pm.sendRequest({
url: authUrl,
method: 'POST',
header: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'grant_type', value: 'client_credentials', disabled: false },
{ key: 'client_id', value: clientId, disabled: false },
{ key: 'client_secret', value: clientSecret, disabled: false }
]
}
}, (err, res) => {
if (err) {
console.error('Token request failed', err);
return;
}
const data = res.json();
if (data.access_token) {
// Store for the current request and for later requests in this run
pm.variables.set('authToken', data.access_token);
pm.environment.set('authToken', data.access_token); // persists in collection runner
}
});
Add the script in the Pre‑request Scripts tab of a request that calls a protected endpoint. Ensure the environment contains authUrl, clientId, and clientSecret.
2. Use the token in the request header
In the Headers tab add:
Authorization: Bearer {{authToken}}
The double‑brace syntax pulls the value from pm.variables at send time.
3. Post‑response script (validate)
// Post‑response script
pm.test('Status is 200', () => {
pm.expect(pm.response.code).to.equal(200);
});
pm.test('Response has expected shape', () => {
const json = pm.response.json();
pm.expect(json).to.have.property('id');
pm.expect(json).to.have.property('name').that.is.a('string');
});
Run the request. The Test Results panel will show the two assertions. If the token fetch exceeds 5 seconds, the sandbox aborts and the request proceeds without a token – you’ll see a 401 and the tests will fail.
Trade‑offs and hard limits
- Fixed 5‑second timeout – long‑running
pm.sendRequestcalls (e.g., a slow auth server) will be killed. You cannot configure this limit. - No npm modules – you only have the built‑in
pmAPI plus a subset of the JS standard library (nofs,cryptobeyondcrypto.getRandomValues, etc.). - Callback‑only async –
pm.sendRequestuses a Node‑style callback; unhandled promise rejections inside the callback may fail silently, so always guard withtry/catchor check theerrargument. - Variable persistence differs – web app = session only; CLI/collection runner = optional file persistence. Design your flows accordingly.
How to verify the behavior yourself
- Open the Hoppscotch web app (https://hoppscotch.io) in a desktop browser.
- Create a new request, switch to the Pre‑request Scripts tab, paste the token‑fetch script above.
- Add the
Authorization: Bearer {{authToken}}header. - Switch to Post‑response Scripts and paste the validation script.
- Define an environment with
authUrl,clientId,clientSecret(use a test OAuth2 endpoint you control). - Send the request. Observe the Test Results panel – two green checks mean the sandbox executed both scripts successfully.
- To test persistence, open the Collection Runner, add the request to a collection, enable “Persist Variables”, run the collection twice, and log
pm.variables.get('authToken')in a second request’s pre‑request script.
If the token fetch takes longer than five seconds, the request will fire without a token and the tests will fail – a clear signal to optimize the auth endpoint or move the fetch out of the sandbox.
Closing takeaway
Hoppscotch’s built‑in scripting engine covers a surprising amount of API test automation: dynamic headers, token refresh, and response assertions all stay inside the client. The 5‑second ceiling and the callback‑only async model are the main constraints; for anything heavier (complex crypto, long polling, external libraries) you’ll still need an external runner. Start by moving your simplest auth‑and‑validate flow into a pre‑/post‑request pair, verify with the steps above, and expand only when the sandbox limits become a bottleneck.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.