Puppeteer: How to Reuse Browser and Page Instances
In this article
Reusing browser and page instances in Puppeteer significantly reduces the overhead of launching a new Chromium process for every task, leading to faster execution times and lower CPU and memory consumption. By maintaining a single browser instance and creating or recycling pages (tabs) as needed, you can scale your automation scripts to handle hundreds of requests without crashing your system.
What You'll Need
- Node.js installed on your local machine or server.
- The
puppeteerorpuppeteer-corepackage installed via npm. - A basic understanding of asynchronous JavaScript (async/await).
- An environment with sufficient RAM to hold a persistent browser process.
Step-by-Step
-
Initialize a Global Browser Variable:
Instead of calling
puppeteer.launch()inside your main function or loop, declare a variable in the global scope or within a singleton class to hold the browser instance. This ensures that the reference to the browser is accessible across different parts of your application. -
Implement a Browser Connection Logic:
Create a helper function that checks if the browser instance already exists. If it does, return the existing instance; if not, launch a new one. This prevents the accidental creation of multiple browser processes.
async function getBrowser() { if (!global.browser) { global.browser = await puppeteer.launch(); } return global.browser; } -
Manage Page Instances:
When you need to perform a task, use
browser.newPage()to create a fresh tab. This provides a clean session for the current task while keeping the main browser process alive. Avoid using a single page instance for entirely different tasks if those tasks require different cookies or local storage, as this can lead to state contamination. -
Execute Tasks and Close Pages:
Perform your scraping or automation logic within the page instance. Once the task is complete, call
await page.close(). Closing the page is critical; if you only close the browser, you lose the persistence, but if you fail to close the page, you will create a memory leak that eventually crashes the browser. -
Handle Browser Crashes:
Implement a try-catch block around your page operations. If a page crash occurs or the browser becomes unresponsive, set your global browser variable to
nulland trigger a relaunch in the next request cycle. -
Graceful Shutdown:
Ensure your application has a cleanup mechanism (such as listening for
SIGINTorSIGTERMsignals) to callawait browser.close()before the Node.js process exits. This prevents zombie Chromium processes from lingering in your system memory.
Common Mistakes
- Forgetting to Close Pages: The most frequent error is calling
browser.newPage()in a loop without callingpage.close(). This will quickly consume all available RAM. - Using a Single Page for Different Users: Using one page instance for multiple unrelated tasks can lead to session leakage, where cookies from one user session affect the next.
- Launching the Browser Inside a Loop: Placing
puppeteer.launch()inside afororwhileloop creates a new OS process every iteration, which is extremely resource-intensive and slow. - Ignoring the Browser Disconnect Event: Failing to listen for the
disconnectedevent means your app might try to use a dead browser instance, resulting in "Protocol error: Target closed" exceptions.
Tips
- Use Browser Contexts: For better isolation than a single page but less overhead than a new browser, use
browser.createIncognitoBrowserContext(). This allows you to have separate cookie jars and caches for different tasks within the same browser instance. - Optimize Launch Arguments: Use flags like
--no-sandboxand--disable-setuid-sandboxin your launch options to reduce overhead in Linux environments. - Limit Concurrent Pages: Implement a queue or a semaphore to limit the number of open pages. Even with a reused browser, opening 50 pages simultaneously can freeze the CPU.
- Disable Unnecessary Assets: Use
page.setRequestInterception(true)to block images, CSS, and fonts if you only need the HTML content, further reducing the memory footprint of each reused page.
Troubleshooting
If you encounter "Protocol error: Target closed", it usually means the browser process crashed or was killed by the OS (often due to Out-of-Memory errors). To fix this, implement a check to see if browser.isConnected() is true before attempting to create a new page. If it returns false, re-initialize the browser.
If you notice memory usage climbing steadily despite closing pages, check for lingering page.on('console') or page.on('request') listeners. These can sometimes create closures that prevent the page object from being garbage collected. Ensure you remove listeners or use a fresh page instance for every operation.
If the browser hangs during the close() operation, try setting a timeout for the close command or ensure that all active network requests are aborted before closing the page.
Frequently Asked Questions
Is it better to reuse the browser or the page?
It is best to reuse the browser instance and create/destroy page instances. Reusing a single page for different tasks can lead to cache and cookie contamination, while restarting the browser for every page is too slow.
How many pages can one browser instance handle?
This depends on your system RAM. Generally, a standard server can handle 10-20 concurrent pages comfortably, but you should monitor memory usage and implement a limit to avoid crashes.
Do reused browser instances share cookies?
Yes, by default, pages created from the same browser instance share the same profile and cookies. To avoid this, use Incognito Browser Contexts.
Will reusing the browser slow down over time?
If you properly close pages and clear memory, it should remain stable. However, Chromium can occasionally leak memory over long periods; it is a good practice to restart the browser instance every few hundred tasks.
Can I connect to an already running browser?
Yes, by using puppeteer.connect({ browserWSEndpoint: '...' }), you can attach Puppeteer to a browser instance that was started externally with the remote-debugging-port flag.