Cypress · Browser testing end to end
How do you manage cookies and local storage in Cypress?
Short answer
Use cy.getCookie, cy.setCookie and cy.clearCookies for cookies, and cy.window with localStorage or the cy.getAllLocalStorage helpers for storage. Local storage is origin-scoped, so visit the domain first.
Cookies and web storage are browser state that tests often need to set up or inspect. Cookies are available through dedicated Cypress commands. Local and session storage are accessed through the window, or through the convenience commands Cypress added for reading and clearing them across origins.
cy.visit("/");
cy.setCookie("theme", "dark");
cy.getCookie("theme").should("have.property", "value", "dark");
cy.window().then((win) => {
win.localStorage.setItem("onboarding", "done");
expect(win.localStorage.getItem("onboarding")).to.eq("done");
});
cy.clearCookies();
cy.clearLocalStorage();Useful commands
- cy.getCookie, cy.getCookies, cy.setCookie and cy.clearCookie
- cy.clearCookies clears cookies for the current domain or all domains
- cy.getAllLocalStorage and cy.clearAllLocalStorage work across origins
- cy.getAllSessionStorage and cy.clearAllSessionStorage do the same for session storage
- A configured baseUrl lets Cypress know the cookie domain without an explicit visit
A cookie set with cy.setCookie requires a URL or a configured baseUrl so Cypress knows the domain. Local storage is stricter: the page must have an origin. Calling localStorage from a blank page throws or targets the wrong origin.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why must you visit a page before setting local storage?
- 2What is the difference between clearCookies and clearing all cookies?
- 3How do you inspect local storage for a second origin?
- 4Does test isolation clear cookies automatically?
Say it in the interview
I use the cookie commands for cookies and cy.window for local or session storage. Storage belongs to an origin, so I visit the app first. Cypress also has getAllLocalStorage and clearAllLocalStorage helpers for multiple origins. Because test isolation clears this state, I set it up in beforeEach or use cy.session when it represents a login.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Cypress mock interview and get scored feedback on depth, clarity and confidence.