User Agents

Web browsers and everyday web tech, explained

Detect Headless Browsers & Scraping Bots

· 5 min read · Browsers

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

Detecting headless browsers and web scraping bots helps you protect your site from automated abuse, credential stuffing, and content theft. This guide shows practical, code-level techniques you can implement today, from simple JavaScript checks to advanced behavioral analysis. You don't need a PhD—just a basic understanding of HTTP and client-side scripting.

What You'll Need

  • A web server (Apache, Nginx, or any backend that can serve custom headers)
  • Ability to add JavaScript to your pages (for client-side checks)
  • Access to server logs for testing (or a tool like Chrome DevTools)
  • Basic knowledge of HTTP headers and browser developer tools

Step-by-Step

  1. Start with user-agent inspection. The simplest check: look at the User-Agent header. Headless browsers often have telltale strings like HeadlessChrome or omit browser identifiers. In your server-side code (e.g., PHP, Python, Node), parse the header and flag suspicious ones. Example regex: /HeadlessChrome|PhantomJS|python-requests|curl\//i. But remember, this is easily spoofed—treat it as a first filter, not a definitive test.
  2. Check for missing browser features. Real browsers support certain APIs. In your frontend JavaScript, test for properties like window.chrome (in Chrome), navigator.webdriver (true in most headless browsers), and window.outerWidth (often 0 in headless). Send the results back to your server via an AJAX call or a hidden form field. Example: if (navigator.webdriver) { /* flag */ }.
  3. Analyze HTTP headers beyond User-Agent. Look at Accept-Language, Accept-Encoding, and Sec-Fetch-* headers. Real browsers send consistent values; bots often omit or send inconsistent ones. For instance, a headless Chrome might send Sec-Fetch-Dest: document correctly, but many custom scrapers don't. Log these headers and compare patterns.
  4. Implement a JavaScript challenge. Serve a page that requires JavaScript execution to set a cookie. For example, generate a random token, set it via JavaScript, and then have the page reload. If the cookie isn't present on reload, it's likely a bot that doesn't execute JS. This is the basis of many anti-bot systems.
  5. Monitor request patterns. Analyze server logs for high request rates, single IPs hitting many pages in seconds, or requests with identical timing intervals. Scrapers are often faster and more regular than humans. Use a simple rate limiter (e.g., 10 requests per second per IP) and block or throttle those that exceed it.
  6. Check for mouse and scroll events. On your pages, track user interactions. Real users move the mouse, scroll, and click. Headless browsers often don't. Use JavaScript to record these events and send a beacon to your server. If a session has zero interactions, flag it.
  7. Use a canvas fingerprint test. Headless browsers often render canvas differently or not at all. Draw a known image to a canvas and extract its data URL. Compare it to a known-good value from a real browser. If it's missing or different, it's suspicious. Example: canvas.toDataURL() returns a long string; if it's empty, likely headless.
  8. Combine signals into a score. Don't rely on a single check. Assign points to each detection (e.g., user-agent flag +5, missing webdriver +10, no mouse events +15). If the total exceeds a threshold (say 20), treat it as a bot. This reduces false positives.
  9. Test your detection. Use a real browser (Chrome, Firefox) and a headless browser (e.g., Puppeteer with headless: true) to visit your test page. Verify that the real one passes and the headless one is flagged. Adjust thresholds as needed.

Common Mistakes

  • Relying only on User-Agent. It's trivial to spoof. A bot can send a normal Chrome user-agent and bypass that check.
  • Blocking all headless browsers. Some legitimate users (e.g., accessibility tools) use headless browsers. Over-blocking can hurt real users.
  • Ignoring false positives. A user with JavaScript disabled or an old browser might fail your checks. Always have a fallback (e.g., CAPTCHA) instead of a hard block.
  • Not testing on mobile. Mobile browsers have different fingerprints. Your checks might flag real mobile users.

Tips

  • Use a multi-layered approach. Combine server-side headers, client-side JS, and behavioral analysis for best results.
  • Keep a whitelist. Allow known good bots (Googlebot, Bingbot) by verifying their IPs via reverse DNS.
  • Log everything. Store the signals you collect (headers, JS results) in a database for later analysis.
  • Update your detection regularly. Headless browsers evolve; check for new properties like navigator.userAgentData.
  • Use a challenge-response for suspicious sessions. Instead of blocking, present a CAPTCHA or a JavaScript puzzle to confirm humanity.

Troubleshooting

  • Your detection is blocking real users. Check your thresholds—lower the score required to trigger a block. Also, add exceptions for users with cookies from a previous successful visit.
  • Bots are still getting through. They may be using a real browser via a remote service (like BrowserStack). In that case, focus on behavioral signals (mouse movements, timing) rather than static checks.
  • JavaScript checks fail because the bot executes JS. Modern headless browsers do execute JS. Instead, use more subtle checks like navigator.plugins.length (often 0 in headless) or window.outerWidth (0 in headless). Test in your own headless browser to see what values you get.
  • Your server-side code can't parse headers. Make sure you're reading the correct header names (case-insensitive). Use a debugging tool like curl -I to see what your server receives.

Frequently Asked Questions

Can I detect all headless browsers with one method?

No. Each method has gaps. For example, navigator.webdriver is reliable in Chrome headless, but Firefox headless may not set it. Use multiple checks and score them.

Is it legal to block scraping bots?

Yes, as long as you're not blocking specific users based on protected characteristics. You can block any traffic you deem harmful, but be careful not to block legitimate search engine crawlers.

What if a bot spoofs all the signals I check?

Sophisticated bots can spoof user-agent, headers, and even JS properties. In that case, behavioral analysis (e.g., mouse movements, time between clicks) is your best bet, but it's harder to implement.

Do these methods work on single-page apps (SPAs)?

Yes, but you need to run the checks after the page loads (e.g., in a DOMContentLoaded event). Also, SPAs may not reload, so your cookie challenge needs to be adapted.

Can I use a third-party service instead of coding this myself?

Yes, there are commercial anti-bot services like Cloudflare Bot Management or DataDome. They handle the complexity, but they cost money and may introduce latency.

Will these checks slow down my site?

Most checks are lightweight—just a few lines of JavaScript and header parsing. The canvas fingerprint is slightly heavier but still negligible. Rate limiting might add a database query per request, but that's manageable.