Pre-request scripts allow you to execute tasks before a request is sent. They can be used to:
- Manipulate environment variables or authentication
- Manipulate the contents of the request
- Send other requests to get the data you need before running the request
Pre-request script examples
The following sections provide pre-request script examples you can use.
Manipulate variables
The insomnia
object serves as a handler for interacting with various types of variables. It offers a range of methods tailored for accessing the base environment and the active environment.
For more details, see Environment variables in scripts.
// set a variable in the selected collection environment
insomnia.environment.set("env", "env value");
// set a variable in the collection base environment
insomnia.baseEnvironment.set("baseEnv", "base env value");
// set a temporary local variable
insomnia.variables.set("var", "var value");
// set a variable in the collection base environment
insomnia.collectionVariables.set("collectionEnv", "collection variable value");
// get values from different scopes
const env = insomnia.environment.get("env");
const variable = insomnia.variables.get("var");
const baseEnv = insomnia.baseEnvironment.get("baseEnv");
// print values
console.log(env, variable, baseEnv);
// unset values
insomnia.environment.unset("env");
insomnia.collectionVariables.unset("baseEnv");
Interpolate variables
The replaceIn()
method can render a string with existing variables. For example, this script interpolates a string with the variable name
:
insomnia.environment.set('name', 'Insomnia User');
const welcome = insomnia.environment.replaceIn("Hello {{name}}.");
console.log(welcome);
Generate a UUID
You can use the uuid
external library to generate a UUID and set it as an environment variable:
const uuid = require('uuid');
insomnia.environment.set('user_id', uuid.v4());
console.log(insomnia.environment.get('user_id'));
Update the current request content
You can use a pre-request scripts to modify the request URL, method, query parameters, headers, or body:
// update the method
insomnia.request.method = 'POST';
// update query parameters
insomnia.request.url.addQueryParams('k1=v1');
insomnia.request.url.addQueryParams('k2=v2');
console.log(insomnia.request.url.getQueryString());
// update headers
insomnia.request.addHeader({key: 'X-Header-Name-1', value: 'value1' });
insomnia.request.addHeader({key: 'X-Header-Name-2', value: 'value2' });
insomnia.request.removeHeader('X-Header-Name-1');
// update the body
insomnia.request.body.update({
mode: 'urlencoded',
urlencoded: [
{ key: 'k1', value: 'v1' },
{ key: 'k2', value: 'v2' },
],
});
// update basic auth
// basic
insomnia.request.auth.update(
{
type: 'basic',
basic: [
{key: 'username', value: 'myName'},
{key: 'password', value: 'myPwd'},
],
},
'basic'
);
Update the current request body
The insomnia.request.body.update()
method allows you to modify the current request body using a specific mode.
The following modes are supported:
Mode |
Example |
---|---|
raw
|
|
file
|
|
formdata
|
|
urlencoded
|
|
graphql
|
|
Update the current request authorization
The insomnia.request.auth
method provides a way to set different AuthN or AuthZ types:
// Set Bearer auth
insomnia.request.auth.update(
{
type: 'bearer',
bearer: [
{key: 'token', value: 'tokenValue'},
{key: 'prefix', value: 'CustomTokenPrefix'},
],
},
'bearer'
);
// Set basic auth
insomnia.request.auth.update(
{
type: 'basic',
basic: [
{key: 'username', value: 'myName'},
{key: 'password', value: 'myPwd'},
],
},
'basic'
);
Update the current proxy
The insomnia.request.proxy
method allows you to get information about the current proxy and update it:
// Print current proxy URL
console.log(insomnia.request.proxy.getProxyUrl());
// Update proxy URL
insomnia.request.proxy.update({
host: '127.0.0.1',
match: 'https://httpbin.org',
port: 8080,
tunnel: false,
authenticate: false,
username: '',
password: '',
});
Update certificates
The insomnia.request.certificate
method allows you to get information about the current certificate and update it:
// Print the original certificate
console.log('key:', insomnia.request.certificate.key.src);
console.log('cert:', insomnia.request.certificate.cert.src);
console.log('passphrass:', insomnia.request.certificate.passphrass);
console.log('pfx:', insomnia.request.certificate.pfx.src);
// Update the certificate
insomnia.request.certificate.update({
disabled: true,
key: {src: 'my.key'},
cert: {src: 'my.cert'},
passphrase: '',
pfx: {src: ''},
});
Send a request
Send another request and set the response code as an environment variable:
const resp = await new Promise((resolve, reject) => {
insomnia.sendRequest(
'https://httpbin.org/anything',
(err, resp) => {
if (err != null) {
reject(err);
} else {
resolve(resp);
}
}
);
});
insomnia.environment.set('prevResponse', resp.code);
You can send requests with different content types:
Content type |
Mode |
Example |
---|---|---|
text/plain
|
raw
|
|
application/octet-stream
|
file
|
|
multipart/form-data
|
formdata
|
|
application/x-www-form-urlencoded
|
urlencoded
|
|
application/graphql
|
graphql
|
|