Designing a Minimal Insomnia‑Based API Client with Environment Variables, OAuth PKCE, and Schema Validation
Shows how to structure an Insomnia workspace for multi‑environment API work, using env var interpolation, native OAuth 2.0 PKCE, pre/post scripts, and inline JSON schema validation.
28 Feb 2026, 12:25 UTC

Overview
When building API integrations you often need a client that works across multiple environments, handles authenticated flows safely, and validates responses without writing external code. Insomnia provides several built‑in features that let you satisfy those needs in a single workspace. This note outlines the requirements, the smallest viable design using those features, the trust and data boundaries involved, how to operate and check the setup, the ways it can fail, and what would prompt a redesign.
Requirements
- Switch between dev, staging, and production contexts without editing each request.
- Automatically obtain and refresh OAuth 2.0 access tokens using PKCE (no secret stored in the workspace).
- Add request‑specific data (e.g., timestamps, signatures) and validate responses against a known JSON schema.
- Keep the workspace portable so it can be shared with teammates or checked into version control.
Smallest Suitable Design
The design uses five Insomnia capabilities that together meet the requirements:
- Environment variable interpolation – define variables such as {{baseUrl}} and {{apiKey}} in an Environment and reference them in request URLs, headers, or body fields.
- Native OAuth 2.0 PKCE flow – configure an Auth helper of type "OAuth 2.0" with PKCE enabled; Insomnia will launch the browser flow, store the token, and refresh it before expiry.
- Pre‑request script – a short JavaScript block that runs before the request is sent, used to add a nonce or timestamp header.
- Post‑response script – a JavaScript block that runs after the response arrives, used to validate the payload against a JSON schema.
- Inline JSON schema validation – attach a schema directly to the request; Insomnia will highlight mismatches in the response viewer.
Below is a concrete example of a GET request that retrieves a user profile.
# Request configuration (shown in Insomnia UI)
GET {{baseUrl}}/users/{{userId}}
Headers:
Authorization: Bearer {{oauthToken}}
X-Request-Id: {{preScript.nonce}}
The environment defines:
- {{baseUrl}} – e.g., https://api.example.com for production, https://staging.api.example.com for staging.
- {{userId}} – a placeholder that can be overridden per request if needed.
- {{oauthToken}} – supplied automatically by the OAuth PKCE auth helper.
The pre‑request script generates a nonce:
// Pre‑request script (runs before sending)
const nonce = Math.random().toString(36).substring(2, 15);
pm.environment.set("nonce", nonce);
The post‑response script validates the JSON shape:
// Post‑response script (runs after receiving)
const schema = {
type: "object",
properties: {
id: { type: "integer" },
name: { type: "string" },
email: { type: "string", format: "email" }
},
required: ["id", "name", "email"]
};
const ajv = new (require("ajv"))();
const validate = ajv.compile(schema);
if (!validate(pm.response.json())) {
throw new Error("Response does not match schema: " + JSON.stringify(validate.errors));
}
Finally, attach the same schema object to the request’s "JSON Schema Validation" field; Insomnia will underline any mismatched fields in the response pane.
Trust and Data Boundaries
- Environment variables are stored in the workspace file; if the file is shared, anyone with access can see the values. Treat them as non‑secret configuration (e.g., base URLs).
- OAuth tokens generated via PKCE are kept in Insomnia’s encrypted token store; they are never written to the workspace file.
- Pre‑ and post‑scripts run inside a sandboxed Node‑like context within Insomnia; they cannot access the host filesystem or make arbitrary network calls outside the current request.
- JSON schema validation is performed locally on the response data; no data is sent to an external service.
Operational Checks
To verify that the design works as intended:
- Select an environment (e.g., "Production") and open the request. The URL and Authorization header should show the interpolated values (you can hover over {{baseUrl}} to see the resolved string).
- Click "Send". Insomnia will launch the OAuth PKCE flow if no valid token exists; after completing the browser consent, the token appears in the Auth helper and is used for the request.
- Inspect the request headers in the log; you should see the generated X‑Request‑Id header matching the nonce created by the pre‑request script.
- In the response viewer, any deviation from the defined schema will be highlighted in red; a valid response will show no validation errors.
- To test token refresh, manually expire the token on the server (e.g., revoke it via an admin endpoint) and send the request again; Insomnia should trigger a new PKCE flow automatically.
Failure Modes
- Missing or mistyped environment variable – Insomnia substitutes an empty string, which often leads to 404 or 401 errors without a clear indication that the variable is undefined. The request will still be sent, making the failure silent unless you inspect the resolved URL.
- Stale OAuth token – If the authorization server revokes a token outside Insomnia’s control (e.g., via admin revocation), the cached token will be used until its expiry time, resulting in 401 responses until Insomnia attempts a refresh (which only occurs on the next scheduled refresh attempt).
- Script errors** – An exception in a pre‑ or post‑script aborts the request or marks the response as invalid, but the error message appears only in the script console; overlooking it can lead to assuming a successful call.
- Schema mismatch** – If the schema is outdated, Insomnia will flag the response, but the request will still be considered successful from a transport perspective, potentially letting invalid data propagate downstream.
When the Design Would Change
- If you need to store true secrets (e.g., private keys) that must never appear in the workspace file, you would move those values out of environment variables into a secret‑management tool and fetch them via a pre‑request script that calls a local agent.
- Should your team require automated contract testing across many endpoints, you might replace the inline JSON schema with an external OpenAPI/Swagger reference and generate test collections programmatically.
- If the API migrates to an authentication method not supported by Insomnia’s native helpers (e.g., mutual TLS with hardware‑bound keys), you would off‑load token handling to an external proxy or custom script.
- When request volume necessitates batch processing or scheduled runs, you might export the Insomnia collection to CLI tools like
insoand integrate it into a CI pipeline rather than relying on manual interaction.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.