Ephemeral vs. Session mode
By default, eachfetch() call runs in ephemeral mode. This is a good fit for one-off requests.
For multi-step flows (like login sequences), use sessions to persist state.
Creating a session
Auto-disposing sessions
UsewithSession() to automatically close the session when done:
Session options
Sessions acceptbrowser, os, proxy, timeout, insecure, and defaultHeaders:
Per-request overrides
Within a session,browser, os, and proxy are fixed at creation time unless you pass an explicit transport for that request.
You can still override per-request values like timeout, headers, redirect, and body:
Cookie management
Sessions automatically handle cookies across requests, but you can also read and write cookies directly.Reading cookies
UsegetCookies(url) to inspect which cookies would be sent to a URL:
getAllCookies() when you want to inspect the entire session jar without already knowing the matching domain/path:
domain, path, sameSite, and expiresAtMs.
Setting cookies manually
UsesetCookie(name, value, url) to inject a cookie into the session jar:
Saving and restoring a jar
UsesetCookies(cookies, url) to put an exported jar back, attributes and all — the way to persist
a logged-in session between runs:
url scopes cookies that have no domain of their own. Those are host-only cookies, and the
jar keeps their host internally rather than returning it, so the export cannot carry it. If the jar
holds host-only cookies from more than one host, give each cookie its own url instead:
Clearing cookies
UseclearCookies() to remove all cookies from the session:
Session isolation
Each session maintains its own:- Cookie jar: cookies are not shared between sessions
- Session identifier and defaults
Best practices
Always close sessions
Call
session.close() or use withSession() to prevent resource leaks.One session per flow
Use a dedicated session for each logical user flow or task.
Parallel isolation
For parallel scraping, create separate sessions to avoid cookie cross-contamination.
Reuse for workflow consistency
Sessions keep one context for multi-step flows.