Write a pre-request script to add an environment variable in Insomnia

Uses: Insomnia
TL;DR

Use pre-request scripts on a collection in Insomnia to carry out pre-processing such as setting variable values, parameters, headers, and body data for requests.

Prerequisites

Download and install Insomnia.

For this tutorial, you’ll need an API Collection in Insomnia. An API Collection is essential for this tutorial to function, but creating one isn’t the focus of this guide. Use the following to add a pre-configured API Collection to Insomnia:

Run in Insomnia

This pre-configured API Collection contains:

Add a pre-request script

In this example, we’ll configure a pre-request script that sets a variable in the request:

  1. In Insomnia, navigate to the “Flight Service 0.1.0” API Collection.
  2. Click the Collection tab in the sidebar.
  3. In the sidebar of your collection, select the Get a specific flight by flight number request.
  4. Click the Scripts tab on the request.
  5. Insomnia provides example pre-request scripts. From the Pre-request tab, click Variable Snippets at the bottom of the pane and select Set an environment variable.
  6. In the example script, replace variable_name with flightNumber and variable_value with KA0285. The script should look like the following:
    insomnia.environment.set("flightNumber", "KA0285");

Validate the pre-request script

Now that we created a pre-request script, we can validate it by sending a GET request to the /flights/{flightNumber} endpoint.

Click Send. You should get a 200 status code and the following response:

{
	"number": "KA0285",
	"route_id": "LHR-SFO",
	"scheduled_arrival": "2024-04-03T11:10:00Z",
	"scheduled_departure": "2024-04-03T22:15:00Z"
}

FAQs

Yes, you can copy and paste your pre-request scripts directly from Postman into an Insomnia pre-request script.

No, pre-request scripts run on the requests inside an API Collection. Every API Collection supports them, including one that holds an OpenAPI spec.

Yes. Insomnia supports variables in request paths through template tags and environment variables.

Define variables in your environment, then reference them directly in a request URL using Liquid syntax, for example:

https://api.example.com/users/{{ user_id }}

For detailed usage examples, go to Requests and Pre-request scripts.

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!