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.

  • ๐Ÿ”˜ Cookie basics: A cookie carries a name, value, domain, path, expiry and the secure and HttpOnly flags.
  • โ˜‘๏ธ Six commands: getCookies, getCookieNamed, addCookie, deleteCookie, deleteCookieNamed and deleteAllCookies cover every operation.
  • โœ… Two-step demo: Step one writes the authentication cookie to a file, step two replays it to authenticate a fresh session.
  • ๐Ÿงช Time saved: Replaying a session cookie removes the login steps from every test case and shortens total execution time.
  • ๐Ÿ› ๏ธ No editing: A cookie cannot be modified in place, so delete the old one and add a rebuilt copy through Cookie.Builder.
  • โš ๏ธ Domain rule: Navigate to the target site before calling addCookie, otherwise the browser rejects the cookie outright.

How to handle cookies in Selenium WebDriver

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.

Guru99 Selenium cookie demo login form with username and password fields

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.

Cookies.data file contents showing the saved session cookie in name value domain path format

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.

FAQs

Two options. Click the Accept button like any element, or set the site’s consent cookie with addCookie before reloading so the banner never renders. The second approach is faster and removes a common source of flaky first steps.

Python uses snake_case equivalents on the driver itself: driver.get_cookies(), driver.get_cookie(name), driver.add_cookie(dict) and driver.delete_all_cookies(). Cookies come back as dictionaries rather than Cookie objects, so read values with square brackets.

Yes. WebDriver talks to the browser through the driver rather than through JavaScript, so HttpOnly cookies are visible via getCookies. Call isHttpOnly and isSecure on the Cookie object to inspect those flags.

AI-assisted analysis groups failing runs by shared signals and often traces intermittent logout failures to an expired or missing session cookie. Some tools also learn which cookies a passing run carries and warn when a session drifts from that baseline.

GitHub Copilot writes the read, write and restore loops quickly, but it frequently reproduces the deprecated new Boolean and new Date constructors. Review every generated snippet against the current Java and Selenium APIs.

No. A session cookie is a live credential, so a committed Cookies.data file lets anyone with repository access impersonate that account. Keep the file out of version control and regenerate it per environment.

Not by default. Each session starts with a clean browser profile, which is exactly why the cookie is written to disk and replayed. Attaching a saved browser profile is the other way to keep a session alive across runs.

Session cookies carry an expiry timestamp and the server also tracks its own session lifetime. Once either lapses the replayed cookie is rejected and the login page returns, so regenerate the stored cookie rather than reusing an old file.

Summarize this post with: