User Agents

Web browsers and everyday web tech, explained

Set Cache-Control Max-Age for Headless Chrome

· 5 min read · Cookies and Cache

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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)

  1. Identify the target assets: Determine which files (CSS, JS, Images) require specific caching durations.
  2. Access your server configuration: Open your .htaccess (Apache), nginx.conf (Nginx), or your application code (Node.js/Express, Python/Django).
  3. Define the max-age value: Decide on the duration in seconds. For example, 31,536,000 seconds equals one year.
  4. 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');.
  5. 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.

  1. Enable Request Interception: In your Puppeteer script, call await page.setRequestInterception(true);.
  2. Set up the Request Listener: Create a listener using page.on('request', ... ) to monitor outgoing requests.
  3. Intercept the Response: Use a library or a custom proxy (like puppeteer-extra-plugin-adblocker or a custom middleware) to modify the response headers. Since standard Puppeteer request.continue() doesn't allow modifying response headers directly, you must use the Chrome DevTools Protocol (CDP).
  4. 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.responseReceived event.
    • Use a proxy tool or a custom CDP wrapper to inject the Cache-Control: max-age=N header into the response before the browser processes it.
  5. Verify the Header: Use page.evaluate() to check the performance entries or use a network logging tool to confirm the max-age is being applied.

Common Mistakes

  • Confusing Request and Response Headers: A common error is attempting to send Cache-Control as a request header. The browser ignores max-age in requests; it only respects it when sent by the server in the response.
  • Ignoring Cache-Busting: If you set a very high max-age and 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-age is always defined in seconds, not milliseconds.

Tips

  • Use a CDN: If you are scaling, use a CDN (like Cloudflare or Akamai) to manage Cache-Control headers at the edge, reducing the load on your origin server.
  • Combine with ETag: Use max-age alongside 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, immutable to 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-cache or Expires that might be taking precedence over Cache-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-age irrelevant. Specify a persistent user data directory using the --user-data-dir flag.
  • 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-Control headers 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.