How to Handle Cookies in Selenium WebDriver
โก Smart Summary
Cookies store user preferences and session identifiers as key-value pairs, and Selenium WebDriver can read, save and replay them so an automated test skips the login screen on every subsequent run.
A HTTP cookie is comprised of information about the user and their preferences. It stores information using a key-value pair. It is a small piece of data sent from a web application and stored in the web browser, while the user is browsing that website.
If you are new to the subject, start with this guide to cookie testing.
Selenium Query Commands for cookies
In Selenium WebDriver, we can query and interact with cookies using the built-in methods below. Every one of them is reached through driver.manage(), which returns the Options interface.
| Selenium Query Commands | Output |
|---|---|
| driver.manage().getCookies(); | Returns the list of all cookies |
| driver.manage().getCookieNamed(arg0); | Returns a specific cookie according to name |
| driver.manage().addCookie(arg0); | Creates and adds the cookie |
| driver.manage().deleteCookie(arg0); | Deletes a specific cookie |
| driver.manage().deleteCookieNamed(arg0); | Deletes a specific cookie according to name |
| driver.manage().deleteAllCookies(); | Deletes all cookies |
Why Handle (Accept) Cookies in Selenium?
Each cookie is associated with a name, value, domain, path, expiry, and the status of whether it is secure or not. In order to validate a client, a server parses all of these values in a cookie.
When testing a web application using Selenium WebDriver, you may need to create, update or delete a cookie.
For example, when automating an online shopping application, you may need to automate test scenarios like place order, view cart, payment information, order confirmation, and so on.
If cookies are not stored, you will need to perform the login action every time before you execute the test scenarios listed above. This will increase your coding effort and execution time.
The solution is to store cookies in a file. Later, retrieve the values of the cookie from this file and add them to your current browser session. As a result, you can skip the login steps in every test case because your driver session has this information in it.
The application server now treats your browser session as authenticated and directly takes you to your requested URL.
How to Handle Cookies in Selenium
We will use https://demo.guru99.com/test/cookie/selenium_aut.php for our demo purpose.
This will be a 2 step process.
Step 1) Login into application and store the authentication cookie generated.
The demo application presents the plain login form shown below.
Step 2) Use the stored cookie to log in to the application again without using a user id and password.
Step 1) Storing cookie information
package CookieExample; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Cookie; public class cookieRead{ public static void main(String[] args) { WebDriver driver; System.setProperty("webdriver.chrome.driver","G:///chromedriver.exe"); driver=new ChromeDriver(); driver.get("https://demo.guru99.com/test/cookie/selenium_aut.php"); // Input Email id and Password If you are already Register driver.findElement(By.name("username")).sendKeys("abc123"); driver.findElement(By.name("password")).sendKeys("123xyz"); driver.findElement(By.name("submit")).click(); // create file named Cookies to store Login Information File file = new File("Cookies.data"); try { // Delete old file if exists file.delete(); file.createNewFile(); FileWriter fileWrite = new FileWriter(file); BufferedWriter Bwrite = new BufferedWriter(fileWrite); // loop for getting the cookie information // loop for getting the cookie information for(Cookie ck : driver.manage().getCookies()) { Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure())); Bwrite.newLine(); } Bwrite.close(); fileWrite.close(); } catch(Exception ex) { ex.printStackTrace(); } } }
โ ๏ธ Version note: the System.setProperty line is kept exactly as the original tutorial wrote it. From Selenium 4.6 onwards, Selenium Manager downloads and configures the matching chromedriver automatically, so that line is no longer required on a current setup. The original code is left untouched below and still compiles.
Code Explanation
- Create a WebDriver instance.
- Visit the website using driver.get(“https://demo.guru99.com/test/cookie/selenium_aut.php”).
- Log in to the application.
- Read the cookie information using
driver.manage().getCookies();
- Store the cookie information using the FileWriter class to write streams of characters, and BufferedWriter to write the text into a file named Cookies.data.
- The Cookies.data file stores all cookie information along with the name, value, domain and path. We can retrieve this information and log in to the application without entering the login credentials.
Once you run the code above, the Cookies.data file is created in the project folder structure. Open the file and you can see the login credential of the AUT saved in cookie format, as the highlighted screen below shows.
Step 2) Using stored cookie to login into the application
Now, we will access the cookie generated in step 1 and use it to authenticate our session in the application.
package CookieExample; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Date; import java.util.StringTokenizer; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class CookieWrite { public static void main(String[] args){ WebDriver driver; System.setProperty("webdriver.chrome.driver","G://chromedriver.exe"); driver=new ChromeDriver(); try{ File file = new File("Cookies.data"); FileReader fileReader = new FileReader(file); BufferedReader Buffreader = new BufferedReader(fileReader); String strline; while((strline=Buffreader.readLine())!=null){ StringTokenizer token = new StringTokenizer(strline,";"); while(token.hasMoreTokens()){ String name = token.nextToken(); String value = token.nextToken(); String domain = token.nextToken(); String path = token.nextToken(); Date expiry = null; String val; if(!(val=token.nextToken()).equals("null")) { expiry = new Date(val); } Boolean isSecure = new Boolean(token.nextToken()). booleanValue(); Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure); System.out.println(ck); driver.manage().addCookie(ck); // This will add the stored cookie to your current session } } }catch(Exception ex){ ex.printStackTrace(); } driver.get("https://demo.guru99.com/test/cookie/selenium_aut.php"); } }
Output: You are taken directly to the login success screen without entering the input user id and password.
NOTE: Use hard refresh in case you see the login page after executing the above script.
โ ๏ธ Java note: the reader script uses new Boolean(String) and new Date(String), both of which the JDK deprecated long ago. On a modern JDK the equivalents are Boolean.parseBoolean(token.nextToken()) and a java.time parser. The original lines are preserved above; treat the note as the modern replacement rather than an edit.
Cookie Attributes and the Selenium Cookie Class
The two scripts above move six fields in and out of a file. Those fields are exactly what the org.openqa.selenium.Cookie class exposes, and knowing them makes the tokenizer loop in Step 2 much easier to read.
| Attribute | Accessor | What it means |
|---|---|---|
| Name | getName() | The key the server looks up, for example JSESSIONID. |
| Value | getValue() | The stored data, usually the session identifier. |
| Domain | getDomain() | The host the browser will send the cookie back to. |
| Path | getPath() | The URL prefix the cookie applies to. |
| Expiry | getExpiry() | The date the cookie dies. A null value means a session cookie. |
| Secure | isSecure() | True when the cookie is only sent over HTTPS. |
| HttpOnly | isHttpOnly() | True when JavaScript on the page cannot read the cookie. |
| SameSite | getSameSite() | Strict, Lax or None. Added in Selenium 4. |
Rather than the six-argument constructor used in Step 2, current code usually builds a cookie through the inner Builder class, which lets you set only the fields you care about.
Cookie sessionCookie = new Cookie.Builder("JSESSIONID", "A1B2C3D4") .domain("demo.guru99.com") .path("/") .isSecure(true) .isHttpOnly(true) .build(); driver.manage().addCookie(sessionCookie);
One rule catches most people out: a cookie object cannot be edited after it is created. To change a value you delete the old cookie and add a rebuilt copy, which is why Builder is so useful.
Cookie original = driver.manage().getCookieNamed("JSESSIONID"); driver.manage().deleteCookie(original); Cookie updated = new Cookie.Builder(original.getName(), "NEW-VALUE") .domain(original.getDomain()) .path(original.getPath()) .isSecure(original.isSecure()) .build(); driver.manage().addCookie(updated);
Common Cookie Errors in Selenium WebDriver and How to Fix Them
Cookie code tends to fail in a small number of predictable ways. The table below lists the ones reported most often, together with the cause and the fix.
| Symptom | Cause | Fix |
|---|---|---|
| InvalidCookieDomainException | addCookie was called before navigating to the site, so the browser is still on about:blank. | Call driver.get on the target domain first, then add the cookie. |
| UnableToSetCookieException | The cookie domain does not match the page currently loaded. | Drop the domain field, or set it to the exact host of the open page. |
| The login page still appears after adding the cookie | The page was rendered before the cookie existed. | Call driver.navigate().refresh(), which is what the NOTE above means by a hard refresh. |
| getCookieNamed returns null | The name is misspelled, or the cookie belongs to a different path or subdomain. | Dump every cookie with getCookies and compare the names. |
| The stored cookie is rejected on a later run | The expiry has passed or the server ended the session. | Regenerate Cookies.data by running Step 1 again. |
If the browser opens and authenticates correctly but the script fails afterwards, the cookie is probably not at fault. Working through exception handling in Selenium is the faster route from that point, and a dedicated Firefox profile is the usual alternative when you want session data to survive without a file at all.


