Insomnia logo
  • Documentation
  • Get Started for Free
    • Introduction to Insomnia
    • Install Insomnia
    • Send Your First Request
    • Import and Export Data
    • Environment Variables
    • Insomnia Workspaces
    • 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 is allowed to be executed before sending a request. In script, some tasks can be executed.

For example, manipulating environment variables, manipulating the active request or sending requests.

Migration from existing Scripts

Pre-request scripts from Postman should just work in Insomnia. But there are still several differences should be taken care:

  • Top level await is 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.
  • Callbacks (such as in the SendRequest method) should be wrapped with Promise, or execution could return before their results have been resolved. (There are examples below).

Please also let us know if you’ve seen some incompatible issues.

Examples

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

Variables Manipulation

insomnia.environment.set("env", "env value");
insomnia.variables.set("var", "var value");
insomnia.baseEnvironment.set("baseEnv", "base env value");
// collectionVariables operations are applied to the base environment
insomnia.collectionVariables.set("collectionEnv", "collection variable value");

const env = insomnia.environment.get("env");
const variable = insomnia.variables.get("var");
const baseEnv = insomnia.baseEnvironment.get("baseEnv");

console.log(env, variable, baseEnv);

insomnia.environment.unset("env");
insomnia.collectionVariables.unset("baseEnv");

Variables Intepolation

insomnia.environment.set('name', 'pre-request script');
const welcome = pm.environment.replaceIn("Hello .");
console.log(welcome);

Update Active Request URL, Query Params or Headers

// 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

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

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

Update Active Request Authorization Type

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

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