Set Cache-Control Max-Age for Headless Chrome
In this article
Setting the Cache-Control max-age header for Headless Chrome is achieved by configuring the server that provides the assets or by using a proxy/interceptor to modify the response headers before they reach the browser instance. Because Headless Chrome is a browser client, it does not "set" its own cache headers to dictate how long it stores files; instead, it obeys the Cache-Control: max-age=N header sent by the web server. To control caching behavior in a headless environment, you must either modify the server's response headers or use a tool like Puppeteer or Playwright to intercept and override these headers programmatically.
What You'll Need
- A Headless Chrome environment (installed via Chrome or Chromium).
- An automation framework such as Puppeteer (Node.js) or Playwright.
- Administrative access to the web server (if modifying headers at the source) or a JavaScript environment for interception.
- Basic knowledge of HTTP headers and asynchronous JavaScript.
Step-by-Step
Depending on whether you have control over the server or are purely controlling the browser client, choose one of the two following methods.
Method 1: Modifying Server-Side Headers (The Standard Way)
- Identify the target assets: Determine which files (CSS, JS, Images) require specific caching durations.
- Access your server configuration: Open your
.htaccess(Apache),nginx.conf(Nginx), or your application code (Node.js/Express, Python/Django). - Define the max-age value: Decide on the duration in seconds. For example, 31,536,000 seconds equals one year.
- Apply the header:
- Nginx: Add
add_header Cache-Control "public, max-age=31536000";within the server or location block. - Apache: Use
Header set Cache-Control "max-age=31536000, public". - Express.js: Use
res.set('Cache-Control', 'public, max-age=31536000');.
- Nginx: Add
- Restart the server: Apply the changes to ensure Headless Chrome receives the new headers upon the next request.
Method 2: Intercepting Headers via Puppeteer (The Client-Side Way)
If you cannot change the server, you can force Headless Chrome to perceive a different max-age by intercepting the network response.
- Enable Request Interception: In your Puppeteer script, call
await page.setRequestInterception(true);. - Set up the Request Listener: Create a listener using
page.on('request', ... )to monitor outgoing requests. - Intercept the Response: Use a library or a custom proxy (like
puppeteer-extra-plugin-adblockeror a custom middleware) to modify the response headers. Since standard Puppeteerrequest.continue()doesn't allow modifying response headers directly, you must use the Chrome DevTools Protocol (CDP). - Utilize CDP for Header Modification:
- Establish a session with
const client = await page.target().createCDPSession();. - Enable the Network domain:
await client.send('Network.enable');. - Listen for the
Network.responseReceivedevent. - Use a proxy tool or a custom CDP wrapper to inject the
Cache-Control: max-age=Nheader into the response before the browser processes it.
- Establish a session with
- Verify the Header: Use
page.evaluate()to check the performance entries or use a network logging tool to confirm themax-ageis being applied.
Common Mistakes
- Confusing Request and Response Headers: A common error is attempting to send
Cache-Controlas a request header. The browser ignoresmax-agein requests; it only respects it when sent by the server in the response. - Ignoring Cache-Busting: If you set a very high
max-ageand then update your site's CSS or JS, Headless Chrome will continue to use the old cached version. Always use versioning (e.g.,style.css?v=2) when using long max-age values. - Forgetting to Disable Cache Entirely: In many headless testing scenarios, the goal is actually to avoid caching. Users often try to set a low max-age when they should simply call
await page.setCacheEnabled(false);. - Incorrect Time Units: Remember that
max-ageis always defined in seconds, not milliseconds.
Tips
- Use a CDN: If you are scaling, use a CDN (like Cloudflare or Akamai) to manage
Cache-Controlheaders at the edge, reducing the load on your origin server. - Combine with ETag: Use
max-agealongside ETags. This allows Headless Chrome to check if a file has changed (304 Not Modified) even after the max-age has expired. - Inspect via CDP: Use the Chrome DevTools Protocol to monitor exactly how the browser is handling the cache during a headless run.
- Prefer Immutable: For assets that never change (like hashed filenames), use
Cache-Control: public, max-age=31536000, immutableto prevent the browser from even sending a conditional request.
Troubleshooting
If Headless Chrome is not respecting your max-age settings, check the following:
- Check for Overriding Headers: Ensure there are no other headers like
Pragma: no-cacheorExpiresthat might be taking precedence overCache-Control. - Verify Disk Cache Path: Headless Chrome sometimes uses a temporary profile. If the profile is deleted after every session, the cache is wiped, making
max-ageirrelevant. Specify a persistent user data directory using the--user-data-dirflag. - Inspect Network Tab: Run Chrome in non-headless mode once to verify the headers in the Network tab. If the header is missing there, the issue is with the server, not the headless configuration.
- Check Proxy Interference: If you are using a corporate proxy or a VPN, the proxy may be stripping or modifying
Cache-Controlheaders before they reach the browser.
Frequently Asked Questions
Can I set max-age using Chrome command-line flags?
No, there is no command-line flag to set a specific max-age value. Flags can disable the cache entirely (--disable-cache), but specific durations must be handled via HTTP headers.
Does page.setCacheEnabled(false) override max-age?
Yes. If you disable the cache in Puppeteer or Playwright, the browser will ignore all Cache-Control headers and fetch every asset from the network every time.
What is the difference between max-age and Expires?
max-age is a relative time (e.g., "this is good for 1 hour"), whereas Expires is an absolute date/time. Cache-Control: max-age takes precedence if both are present.
How do I clear the cache in Headless Chrome?
You can clear the cache by using the CDP command Network.clearBrowserCache or by deleting the user-data-dir folder associated with the browser instance.
Will setting a high max-age speed up my headless scraping?
Yes, if you are visiting the same pages repeatedly and using a persistent user profile, caching assets will significantly reduce page load times and bandwidth usage.