selenium cookie domain mismatch: cannot set cookie
Fixes selenium 'cannot set cookie' errors caused by domain mismatch. Use it when `add_cookie` fails because the driver is on the wrong domain. Not for cookie assertions or session/auth design questions.
TL;DR
Selenium can only set a cookie for the domain the browser is currently on; calling add_cookie before navigating (or while on a different domain) throws the domain mismatch error. The fix is to get() any page on the target domain first, then add the cookie, then navigate to the page that needs it. Strip leading dots from the domain field and make sure the cookie domain matches the current host exactly, subdomains included.
The query
selenium cookie domain mismatch: cannot set cookieUse this when
add_cookiethrows an invalid cookie domain error- Seeding auth/session cookies before a test
- Tests pass locally but fail in an environment with a different host
Not for
- Reading or asserting cookies after login
- HttpOnly cookie limitations (JS cannot touch those either)
- Choosing cookie vs token auth architectures
Steps
- Navigate the driver to any URL on the target domain (even the bare domain root) before touching cookies. Expected output: the browser's current domain matches the cookie's domain.
- Call
add_cookiewith the domain matching the current host (no leading-dot tricks, correct subdomain). Expected output: no error; the cookie is stored. - Navigate to the page under test (or refresh) so the cookie is sent with requests. Expected output: the app sees the session/auth state the cookie provides.
- Verify with
get_cookies()that the cookie exists with the expected domain. Expected output: the cookie list contains your cookie on the right domain.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_B1LKYkK3ToGYHyDD3z64JA
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.