Say good bye to Postman, Insomnia and even your .http-files.
Say hello to programmable API testing.
This is a simple tiny script using a browser to perform token refresh, either up front or headless in background.
You don't need to mess with client ids, secrets, endpoints, OAuth me here and OAuth me there.
Just normal - browser - login.
npm i puppeteer
import { Q } from "./Q.mjs";
const { fetch, getToken } = Q("./user-data", "https://yourapilogin");
console.log(await fetch("https://yourapi/api/stuff"));
console.log(await getToken());
Initially, Puppeteer's browser window allows for API login. Note, the login endpoint may differ from the API's.
Post-login, token is loaded from cache, or Puppeteer operates headlessly, managing token refreshes until cookies or refresh token expires.
For SSO accounts (e.g., Microsoft, Google, GitHub), reuse the user data directory across APIs to minimize login frequency.
fetch from Q enhances the native fetch, invoking getToken upon encountering a 401 (Unauthorized) response:
- Call fetch.
- If a 401 response occurs, call getToken.
- Initiate Puppeteer headlessly, looking for any "Authorization" header.
- If no header is found within 2 seconds, switch to a visible Puppeteer window.
- Store and return the token once the "Authorization" header is detected.
For subsequent runs, if the authorization token is still valid, the process is streamlined, avoiding unnecessary logins. If the token expires or is revoked, Puppeteer refreshes it using the saved user directory, maintaining seamless access.