Read Puppeteer Cookies After Redirects: Full Guide
In this article
To read cookies after Puppeteer finishes redirects, you must use page.waitForNavigation({ waitUntil: 'networkidle0' }) or page.waitForNetworkIdle() before calling page.cookies(). This ensures that the browser has completed all HTTP redirects and that the server has had time to set the final set of cookies in the browser's jar. Because redirects happen rapidly and often involve multiple hops, calling the cookies method immediately after a page.goto() call—without waiting for the network to settle—often results in capturing cookies from an intermediate page rather than the final destination.
What You'll Need
- Node.js installed on your local machine or server.
- The
puppeteerpackage installed via npm (npm install puppeteer). - A target URL that performs one or more redirects (e.g., an OAuth flow or a shortened URL).
- Basic knowledge of JavaScript async/await syntax.
Step-by-Step
- Initialize Puppeteer: Start by launching the browser instance and creating a new page. It is recommended to use
headless: truefor automation, butheadless: falseis helpful for debugging to see the redirects happening in real-time. - Trigger the Redirect: Use
await page.goto(url)to navigate to the starting page. If the redirect is triggered by a button click or a form submission rather than a direct URL load, usepage.click()orpage.type()followed by a submit action. - Implement the Wait Strategy: This is the most critical step. A standard
gotomay resolve as soon as the first response is received, but redirects happen in a chain. Useawait page.waitForNavigation({ waitUntil: 'networkidle0' }). Thenetworkidle0option tells Puppeteer to wait until there are no more than 0 network connections for at least 500ms. This guarantees that the final redirect has landed and all associated cookies have been written to the browser context. - Extract the Cookies: Once the network is idle, call
const cookies = await page.cookies();. This method returns an array of cookie objects containing the name, value, domain, path, expiry, and security flags for all cookies associated with the current page's URL. - Filter for Specific Cookies: Since
page.cookies()returns every cookie for the domain, use the.find()or.filter()array methods to isolate the specific session ID or authentication token you need. For example:const sessionCookie = cookies.find(c => c.name === 'session_id'); - Close the Browser: Always call
await browser.close()to prevent memory leaks and orphaned Chrome processes from running in the background.
Common Mistakes
One of the most frequent errors is relying solely on page.goto(). Many developers assume that because await page.goto(url) is used, the script will wait for the final page. However, if the server sends a 301 or 302 redirect, the initial promise might resolve before the subsequent page has fully loaded its own cookies. This leads to "empty" cookie arrays or arrays containing only the cookies from the redirecting server, not the destination server.
Another mistake is using waitUntil: 'load'. The 'load' event fires when the HTML is parsed, but many modern applications set cookies via asynchronous JavaScript calls or late-stage API responses that happen after the initial load event. Using networkidle0 or networkidle2 is significantly more reliable for cookie extraction because it monitors the actual network traffic rather than just the DOM state.
Developers also often forget to handle the browser context correctly. If you are trying to read cookies across different domains (cross-domain redirects), ensure you are not using a strict BrowserContext that isolates the cookies in a way that prevents them from being accessible to the main page object. While usually not an issue for simple redirects, it becomes a factor in complex multi-tenant environments.
Tips
For high-reliability scripts, implement a retry loop. Sometimes a network hiccup can cause networkidle0 to trigger slightly too early if there is a gap in request timing. Wrapping your cookie extraction in a small loop that checks for the existence of a specific required cookie (e.g., while(!sessionCookie) { ... }) with a maximum timeout can prevent intermittent failures.
If you are dealing with an authentication flow that involves a third-party provider (like Google or Microsoft), use page.setExtraHTTPHeaders() to mimic a real browser more closely. Some redirect chains will fail or loop infinitely if they detect a headless browser, which prevents the final cookies from ever being set. Adding a realistic User-Agent string is often necessary to reach the final redirect destination.
To debug the redirect chain, use the page.on('request', request => console.log(request.url())) listener. This allows you to see every single hop the browser takes. If you see the browser hitting a 404 or an error page during the redirect, you will know why the cookies aren't appearing—the browser never actually reached the page that sets them.
Troubleshooting
Problem: The cookie array is empty even after waiting.
Check if the cookies are set as HttpOnly. While page.cookies() can generally see HttpOnly cookies (because it accesses the browser's internal jar), some security configurations or browser flags might interfere. Ensure you are not attempting to read cookies via page.evaluate(() => document.cookie), as document.cookie cannot access HttpOnly cookies. Always use the Puppeteer API method page.cookies().
Problem: The script times out while waiting for navigation.
This usually happens when a page has a persistent websocket connection or a polling script that keeps the network active, preventing networkidle0 from ever triggering. In this case, switch to networkidle2, which allows up to two active connections. Alternatively, use page.waitForSelector('.some-element') to wait for a specific piece of content that only appears on the final page, which serves as a proxy for the redirect being complete.
Problem: Cookies are present but have the wrong values.
This suggests you are capturing cookies from an intermediate redirect page. Double-check your await sequence. Ensure that the waitForNavigation call is placed after the action that triggers the redirect and before the page.cookies() call. If the redirect is automatic upon page load, the goto call with waitUntil: 'networkidle0' should suffice, but adding an explicit page.waitForTimeout(1000) (though generally discouraged) can help isolate whether the issue is timing-related.
Frequently Asked Questions
Can I read cookies from a different domain after a redirect?
Yes, page.cookies() returns all cookies for the current page's context. If the redirect took you from domain-a.com to domain-b.com, the cookies returned will be those for domain-b.com. To get cookies for a specific URL, you can pass that URL as an argument to page.cookies(url).
What is the difference between networkidle0 and networkidle2?
networkidle0 waits until there are zero active network connections for 500ms. networkidle2 waits until there are no more than two active connections. Use networkidle2 for pages that have constant background polling or analytics pings that never stop.
Do I need to use a proxy to capture cookies from redirects?
No, a proxy is not required for reading cookies. Puppeteer interacts directly with the browser's cookie store. A proxy is only necessary if the target site blocks your IP address or requires a specific geographic location to trigger the redirect.
How do I handle cookies that expire very quickly?
If cookies expire in seconds, you must minimize the time between the redirect and the extraction. Avoid using long waitForTimeout calls and instead use page.waitForFunction() to detect the exact moment a specific cookie is set in the browser's storage.
Can I save these cookies for later use?
Yes, you can save the array returned by page.cookies() to a JSON file. To reuse them in a future session, use page.setCookie(...cookies) before navigating to the site, which allows you to bypass the redirect/login flow entirely.