How to Save and Load Cookies in Puppeteer for Session Persistence
Answer
In Puppeteer, cookies can be saved using page.cookies() after authentication and restored later using page.setCookie(). This allows session persistence across browser runs, avoiding repeated logins and maintaining authenticated states in automation or scraping workflows.
Detailed Explanation
Cookies are small data pieces stored by websites to maintain session identity, user preferences, and authentication state. When a user logs in, the server issues session cookies that are attached to subsequent HTTP requests. In headless browser automation, these cookies are not automatically persisted across browser instances unless explicitly saved.
Puppeteer launches a fresh browser context by default, meaning every session starts without prior authentication data. To overcome this limitation, developers extract cookies from a logged-in session using the DevTools API exposed through Puppeteer. These cookies can then be serialized and stored externally (e.g., JSON file). On a new run, they are re-injected before navigation, restoring the authenticated session as long as the cookies are still valid.
This technique is widely used in web scraping, automated testing, and bot workflows where maintaining login continuity is essential. However, cookies may expire, become invalidated by server-side rotation, or be bound to specific domains and security attributes such as HttpOnly or SameSite, which must be respected during restoration.
Solutions / Methods
- Extract cookies after login: Use
await page.cookies()once authentication is complete, then store the result as JSON for reuse in future sessions. - Restore cookies before navigation: Load stored cookie data and apply it using
await page.setCookie(...cookies)before visiting protected pages to maintain session state. - Use automated CAPTCHA handling when sessions break: Some websites invalidate sessions with challenges like reCAPTCHA or Cloudflare protection. In such cases, automated CAPTCHA solving services such as CapSolver can help restore access flow by resolving verification steps programmatically during login or session renewal.
Best Practice / Tips
- Always match cookies to the correct domain before restoring them.
- Avoid mixing cookie sets between different websites to prevent authentication conflicts.
- Prefer persistent browser contexts when long-term sessions are required.
- Handle expired cookies gracefully by re-authenticating or triggering automated verification flows when needed.
š Related:
Use code
FAQwhen signing up at CapSolver to receive an additional 5% bonus on your recharge.
CapSolver FAQ ā capsolver.com
