Insomnia logo
  • Documentation
  • Get Started for Free
    • Introduction to Insomnia
    • Install Insomnia
    • Send Your First Request
    • Import and Export Data
    • Environment Variables
    • Insomnia Accounts
    • Forgotten Passphrase
    • Organizations
    • Enable Enterprise membership
    • Configuring EE SSO
    • Integrating Insomnia Enterprise with Okta SAML 2.0
    • Integrating Insomnia Enterprise with Microsoft Azure/Entra ID SAML 2.0
    • Insomnia Whitelisting Guide for Enterprise Users
    • Insomnia Subscriptions
    • Insomnia Subscription Management
    • Scratch Pad Tutorial
    • Requests
    • Responses
    • Request Collections
    • Request Timeouts
    • Chaining Requests
    • Post CSV Data
    • SOAP Requests
    • gRPC
    • WebSocket Support
    • Get Started with Documents
    • Design Documents
    • Linting
    • GraphQL for OpenAPI
    • Migrate from Designer
    • Unit Testing
    • Stress Testing
    • Insomnia Storage Options Guide
    • Sync with Insomnia Cloud
    • Sync with Git
    • Key Security Features
    • Security Standards
    • Signup and Authentication
    • Analytics Collected
    • End to End Data Encryption
    • Authentication
    • Client Certificates
    • Generate Code Snippet
    • Cookie Management
    • Encoding
    • GraphQL Queries
    • Run in Insomnia Button
    • Key Maps
    • Proxy
    • Introduction to Plugins
    • Context Object Reference
    • Template Tags
    • Hooks and Actions
    • Custom Themes
    • FAQ
    • Application Data
    • SSL Validation
    • Password Recovery
    • Introduction to Inso CLI
    • Install Inso CLI
    • CLI Command Reference
      • inso generate config
      • inso run test
      • inso lint spec
      • inso export spec
      • inso script
      • OpenAPI Spec Reference
      • Using Custom Linting with Inso CLI
    • Configuration
    • Inso CLI on Docker
    • Continuous Integration
    • Kong Declarative Config (for decK)
    • Kong for Kubernetes
    • Insomnia Pre-request Script Overview
    • Insomnia API Mocking Overview

Insomnia Pre-request Script Overview

The pre-request script feature allows users to execute tasks before a request is sent.

This applies for example to cases where you might need:

  • Manipulate environment variables, authentication, …
  • Manipulate the contents a given request
  • Send other requests before that will provide data you need to run a given request

Migrating from Postman pre-request scripts

Pre-request scripts exported from Postman should also work when imported into Insomnia.

There are some differences to be aware about:

  • Top level awaits are allowed.
  • Global environment insomnia.globals and iteration data insomnia.iterationData are not supported yet.
  • CollectionVariables is mapped to baseEnvironment in Insomnia.
  • Deprecated postman interfaces are not supported yet, such as postman.setEnvironmentVariable.

If you notice any incompatibility issues, please report these by create a new issue on Github.

Examples

These example snippets are some common tasks which could be helpful in scripting:

Variables Manipulation

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.

// set a variable in environment
insomnia.environment.set("env", "env value");
// set a variable in base environment
insomnia.baseEnvironment.set("baseEnv", "base env value");
// set a variable in variables
insomnia.variables.set("var", "var value");
// collectionVariables operations are applied to the 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");

Variables Interpolation

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', 'pre-request script');
const welcome = pm.environment.replaceIn("Hello .");
console.log(welcome);

Update Active Request URL, Query Params or Headers

It is also allowed to modify the active request. In the pre-request script, “the active request” represents the upcoming request that is about to be executed. insomnia.request allows users to manipulate different aspects of the request configuration before its execution, enabling them to fine-tune parameters or make adjustments as needed.

// manipulating method
insomnia.request.method = 'POST';

// manipulating query params
insomnia.request.url.addQueryParams('k1=v1');
insomnia.request.url.addQueryParams('k2=v2');
console.log(insomnia.request.url.getQueryString());

// manipulating 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 Active Request Body

Of course, the pre-request script also provides a way to modify the active request’s body. Currently it supports several modes:

  • raw
  • file
  • formdata
  • urlencoded
  • graphql

The raw mode is allowed to set any string value as the body, by specifying the raw field.

// raw content
insomnia.request.body.update({
 mode: 'raw',
 raw: 'rawContent',
});

In the urlencoded mode, key value pairs will be added and the body will be sent as application/x-www-form-urlencoded.

// urlencoded content
insomnia.request.body.update({
 mode: 'urlencoded',
 urlencoded: [
   { key: 'k1', value: 'v1' },
   { key: 'k2', value: 'v2' },
 ],
});

This is an example of modifying the active GQL request to github.

insomnia.request.url = 'https://api.github.com/graphql';
insomnia.request.method = 'POST';
insomnia.request.body.update({
  mode: 'graphql',
  graphql: {
    query: `query($number_of_repos:Int!) {
      viewer {
        name
     repositories(last: $number_of_repos) {
           nodes {
             name
       }
     }
   }
}`,
    operationName: undefined,
    variables: {   "number_of_repos": 3},
  },
});

It also supports sending a file from local:

insomnia.request.body.update({
 mode: 'file',
 file: "/Users/<user name>/tmp.csv",
});

Finally, this is an example of multipart/form-data request.

insomnia.request.method = 'POST'
insomnia.request.body.update({
  mode: 'formdata',
  header: {
    'Content-Type': 'multipart/form-data',
  },
  formdata: [
    { key: 'k1', type: 'text', value: 'v1' },
    { key: 'k2', type: 'file', value: "/Users/<user name>/tmp.csv" },
  ],
});

Update Active Request Authorization Type

insomnia.request.auth provides a way to set different authn or authz types.

This is an example of setting bearer auth.

// bearer
insomnia.request.auth.update(
    {
        type: 'bearer',
        bearer: [
            {key: 'token', value: 'tokenValue'},
            {key: 'prefix', value: 'CustomTokenPrefix'},
        ],
    },
    'bearer'
);

This is an example of setting `basic` auth.
// basic
insomnia.request.auth.update(
    {
        type: 'basic',
        basic: [
            {key: 'username', value: 'myName'},
            {key: 'password', value: 'myPwd'},
        ],
    },
    'basic'
);

Update the Proxy Temporarily

// print current proxy url
console.log(insomnia.request.proxy.getProxyUrl());

// update it
insomnia.request.proxy.update({
 host: '127.0.0.1',
 match: 'https://httpbin.org',
 port: 8080,
 tunnel: false,
 authenticate: false,
 username: '',
 password: '',
});

Update the Certificates

// print the original one
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
insomnia.request.certificate.update({
    disabled: true,
    key: {src: 'my.key'},
    cert: {src: 'my.cert'},
    passphrase: '',
    pfx: {src: ''},
});

Send a Request (Simple Mode)

Please make sure that callbacks are wrapped with Promise.

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);

Send a Request (Advanced Mode)

Send a request with raw content.

const rawReq = {
    url: 'httpbin.org/anything',
    method: 'POST',
    header: {
        'Content-Type': 'text/plain',
    },
    body: {
        mode: 'raw',
        raw: 'rawContent',
    },
};

const resp = await new Promise((resolve, reject) => {
    insomnia.sendRequest(
        rawReq,
        (err, resp) => {
            if (err != null) {
                reject(err);
            } else {
                resolve(resp);
            }
        }
    );
});

Send a request with urlencoded content.

const urlencodedReq = {
    url: 'httpbin.org/anything',
    method: 'POST',
    header: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
            { key: 'k1', value: 'v1' },
            { key: 'k2', value: 'v2' },
        ],
    },
};

const resp = await new Promise((resolve, reject) => {
    insomnia.sendRequest(
        urlencodedReq,
        (err, resp) => {
            if (err != null) {
                reject(err);
            } else {
                resolve(resp);
            }
        }
    );
});

Send a GraphQL request.

const gqlReq = {
    url: 'httpbin.org/anything',
    method: 'POST',
    header: {
        'Content-Type': 'application/graphql',
    },
    body: {
        mode: 'graphql',
        graphql: {
            query: 'query',
            operationName: 'operation',
            variables: 'var',
        },
    },
};

const resp = await new Promise((resolve, reject) => {
    insomnia.sendRequest(
        gqlReq,
        (err, resp) => {
            if (err != null) {
                reject(err);
            } else {
                resolve(resp);
            }
        }
    );
});

Send a request with application/octet-stream content.

const fileReq = {
    url: 'httpbin.org/anything',
    method: 'POST',
    header: {
        'Content-Type': 'application/octet-stream',
    },
    body: {
        mode: 'file',
        file: "${getFixturePath('files/rawfile.txt')}",
    },
};

const resp = await new Promise((resolve, reject) => {
    insomnia.sendRequest(
        fileReq,
        (err, resp) => {
            if (err != null) {
                reject(err);
            } else {
                resolve(resp);
            }
        }
    );
});

Send a request with application/octet-stream content.

const formdataReq = {
    url: 'httpbin.org/anything',
    method: 'POST',
    header: {},
    body: {
        mode: 'formdata',
        formdata: [
            { key: 'k1', type: 'text', value: 'v1' },
            { key: 'k2', type: 'file', value: "${getFixturePath('files/rawfile.txt')}" },
        ],
    },
};

const resp = await new Promise((resolve, reject) => {
    insomnia.sendRequest(
        formdataReq,
        (err, resp) => {
            if (err != null) {
                reject(err);
            } else {
                resolve(resp);
            }
        }
    );
});

External libraries

The require method grants access to the built-in library modules within the scripts. Below is a list of the available libraries.

  • ajv
  • atob
  • btoa
  • chai
  • cheerio
  • crypto-js
  • csv-parse
  • lodash
  • moment
  • postman-collection
  • tv4
  • uuid
  • xml2js

The following NodeJS modules are also available:

  • assert
  • buffer
  • events
  • path
  • querystring
  • punycode
  • stream
  • string-decoder
  • timers
  • url
  • util

And this is an example of using uuid to generate an id:

const uuid = require('uuid');
insomnia.environment.set('user_id', uuid.v4());
console.log(insomnia.environment.get('user_id'));
Edit this page
Report an issue
    COMPANY
  • Insomnia
  • Blog
  • Changelog
  • Pricing
  • Careers
    PRODUCTS
  • Insomnia
  • Inso (CLI)
    RESOURCES
  • Sign In
  • Documentation
  • Support
    LEGAL
  • Privacy Policy
  • Terms & Conditions
© Kong Inc. 2021