Log In Once via the API and Reuse the Session Cookie
Skip the login form in every test: authenticate over HTTP, inject the session cookie into the browser, and land on an authenticated page in under a second.
Problem
Every test starts by typing a username and password into the login form. That costs 3 to 8 seconds per test, multiplies across a suite of hundreds, and means one broken login page fails everything. Only the login tests themselves should exercise the form.
Solution
Call the authentication endpoint with an HTTP client, take the session cookie from the response, open any lightweight page on the app’s domain, add the cookie to the browser, then navigate to the page under test.
import java.net.URI;import java.net.http.*;import java.net.CookieManager;import java.net.HttpCookie;
public static void loginViaApi(WebDriver driver, String baseUrl, String user, String pass) throws Exception { CookieManager jar = new CookieManager(); HttpClient http = HttpClient.newBuilder().cookieHandler(jar).build();
HttpRequest login = HttpRequest.newBuilder(URI.create(baseUrl + "/api/auth/login")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( "{\"username\":\"" + user + "\",\"password\":\"" + pass + "\"}")) .build(); HttpResponse<String> res = http.send(login, HttpResponse.BodyHandlers.ofString()); if (res.statusCode() != 200) throw new IllegalStateException("API login failed: " + res.statusCode());
HttpCookie session = jar.getCookieStore().getCookies().stream() .filter(c -> c.getName().equals("SESSIONID")) .findFirst().orElseThrow();
// 1. Put the browser on the domain (a cheap page: 404s and /robots.txt are fine) driver.get(baseUrl + "/robots.txt"); // 2. Add the cookie driver.manage().addCookie(new Cookie.Builder(session.getName(), session.getValue()) .path("/") .isHttpOnly(true) .isSecure(baseUrl.startsWith("https")) .sameSite("Lax") .build()); // 3. Go where the test actually starts driver.get(baseUrl + "/dashboard");}import requests
def login_via_api(driver, base_url, user, password): s = requests.Session() res = s.post(f"{base_url}/api/auth/login", json={"username": user, "password": password}, timeout=10) res.raise_for_status() session_value = s.cookies.get("SESSIONID") assert session_value, "No SESSIONID cookie in login response"
driver.get(f"{base_url}/robots.txt") # 1. get onto the domain driver.add_cookie({ # 2. add the cookie "name": "SESSIONID", "value": session_value, "path": "/", "httpOnly": True, "secure": base_url.startswith("https"), "sameSite": "Lax", }) driver.get(f"{base_url}/dashboard") # 3. start the testasync function loginViaApi(driver, baseUrl, user, password) {const res = await fetch(`${baseUrl}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: user, password }),});if (!res.ok) throw new Error(`API login failed: ${res.status}`);
// Node 20+: getSetCookie() returns each Set-Cookie header separatelyconst raw = res.headers.getSetCookie().find((c) => c.startsWith('SESSIONID='));if (!raw) throw new Error('No SESSIONID cookie in login response');const value = raw.split(';')[0].split('=').slice(1).join('=');
await driver.get(`${baseUrl}/robots.txt`);await driver.manage().addCookie({ name: 'SESSIONID', value, path: '/', httpOnly: true, secure: baseUrl.startsWith('https'), sameSite: 'Lax',});await driver.get(`${baseUrl}/dashboard`);}using System.Net;using System.Net.Http.Json;
public static async Task LoginViaApiAsync(IWebDriver driver, string baseUrl, string user, string pass){ var jar = new CookieContainer(); using var http = new HttpClient(new HttpClientHandler { CookieContainer = jar });
var res = await http.PostAsJsonAsync($"{baseUrl}/api/auth/login", new { username = user, password = pass }); res.EnsureSuccessStatusCode();
var session = jar.GetCookies(new Uri(baseUrl))["SESSIONID"] ?? throw new InvalidOperationException("No SESSIONID cookie in login response");
driver.Navigate().GoToUrl($"{baseUrl}/robots.txt"); driver.Manage().Cookies.AddCookie(new OpenQA.Selenium.Cookie( session.Name, session.Value, null, "/", null, baseUrl.StartsWith("https"), // secure true, // httpOnly "Lax")); // sameSite driver.Navigate().GoToUrl($"{baseUrl}/dashboard");}Why It Works
The server only cares that the browser presents a valid session cookie; it does not know or care how the cookie got there. WebDriver’s add-cookie command writes straight into the browser’s cookie store, including HttpOnly cookies that page JavaScript could never set. You pay for one HTTP round trip instead of a page load, a form fill and a redirect chain.
| Approach | Typical cost per test | Fails when |
|---|---|---|
| Fill the login form | 3-8 s | Login page changes, MFA prompt, slow identity provider |
| API login + cookie | 0.2-0.5 s | Auth endpoint changes (rare, versioned) |
| Reuse one cookie for the whole worker | ~0 s | Tests mutate session state or log out |
Variations
- Token in localStorage instead of a cookie. Single-page apps often keep a JWT in
localStorage. Open the domain, thenexecuteScript("localStorage.setItem('access_token', arguments[0])", token), then navigate. See Cookies and Storage. - Cache per worker. Log in once per parallel worker (a session-scoped fixture or a
@BeforeAll), keep the cookie value, and inject it at the start of each test. Use one test user per worker so sessions do not collide.
Gotchas
- You must be on the domain first. Adding a cookie on
about:blankor a different domain throwsInvalidCookieDomainException(orunable to set cookie). Use a fast, static URL on the same domain:/robots.txt,/favicon.icoor a known 404 page. - Domain attribute. Omit
domainunless you need a parent-domain cookie. If you set it, it must match the current host under RFC 6265 rules; since Selenium 4.52 the Python bindings follow those rules strictly, so a leading-dot mismatch that used to slip through now fails. Secureon plain HTTP. A cookie markedSecureis silently dropped on anhttp://page. Match the flag to the scheme, as above.- CSRF tokens. Some apps also need an anti-forgery cookie or header. Copy every cookie the login response set, not just the session one.
- Keep one real login test. The form still needs coverage; just not in every test.
Learn the theory
- Cookies, Local Storage and Session Storage Read, add and delete cookies, reuse a login session across tests, inspect localStorage and sessionStorage, and understand the domain and secure-flag rules that make cookie injection fail.
- Speeding Up Test Suites Where Selenium suites lose time and how to get it back: measure first, then cut command count, skip UI you are not testing, fix waits, parallelise, block third-party traffic, and shrink the suite itself.