How to make a CAPTCHA GDPR compliant: legal basis, cookie consent and code

Seven steps to run a CAPTCHA lawfully under GDPR and the ePrivacy cookie rule: legal basis, privacy policy, cookie consent, data minimisation and code examples.

Hugh Parry
Hugh Parry

Privacy Updated 4 min read

Bots make up nearly half of all internet traffic, and malicious bots account for 32%. CAPTCHAs help block automated attacks, but some silently collect user data, which creates privacy risks.

Knowing how to make CAPTCHA GDPR compliant matters for avoiding fines, and also for ethical web practices and user trust. If your CAPTCHA collects data you have not accounted for, every form submission can violate privacy laws unknowingly.

In this article, we will:

  • Master these seven steps for GDPR-compliant CAPTCHAs
  • Apply these privacy-focused code solutions
  • Find answers to your compliance questions

7 Essential Steps to Create GDPR-Compliant CAPTCHAs That Protect Both Users and Your Business

Before you implement anything, you need to understand what the GDPR requires of your CAPTCHA systems:

Data Processing Principles: Any CAPTCHA must adhere to the core GDPR principles of lawfulness, fairness, transparency, purpose limitation, data minimisation, accuracy, storage limitation, integrity, and accountability.

CAPTCHA systems often collect various types of data, including:

To see how much of this each provider collects, and where it is processed, read our comparison of GDPR-compliant CAPTCHAs.

Step-by-Step Process to Ensure GDPR-Compliant CAPTCHA Implementation

image2Follow these steps to turn your CAPTCHA from a compliance risk into a privacy asset.

You must have a legitimate reason to process personal data through your CAPTCHA. The two most applicable legal bases are:

  • Legitimate interest: Protecting your website from spam and bot attacks
  • Consent: Explicit user agreement to data processing

If you rely on legitimate interest for your CAPTCHA, this requires documenting your legitimate interest assessment to show that your security interests outweigh the possible privacy impact.

Step 2: Update Your Privacy Policy

Your privacy policy must explicitly mention:

  • That you use CAPTCHA technology
  • What data is collected
  • How long data is retained
  • The legal basis for processing
  • Which third parties (if any) have access to the data

Be transparent about what happens behind the scenes when users interact with your CAPTCHA.

Step 3: Choose a GDPR-Friendly CAPTCHA Solution

CAPTCHA technologies differ a great deal on privacy. Look for:

hCaptcha and newer versions of reCAPTCHA have made significant improvements in GDPR compliance but require careful configuration.

Step 4: Implement Data Minimization

Collect only what you absolutely need to tell a human from a bot:

  • Configure your CAPTCHA to collect minimal personal data
  • Set the shortest possible data retention periods
  • Anonymise or pseudonymise data where possible
  • Disable unnecessary tracking features

You may need to work with your CAPTCHA provider to change settings beyond the defaults.

Step 5: Ensure Accessibility Alongside Compliance

GDPR compliance should not come at the expense of accessibility. Implement:

  • Multiple verification methods (audio alternatives, simple puzzles)
  • Clear instructions for all users
  • Reasonable accommodations for users with disabilities

This way your CAPTCHA does not discriminate against anyone and still stays compliant.

Step 6: Document Your Compliance Measures

Documentation is crucial for demonstrating compliance. Maintain records of:

  • Your CAPTCHA implementation decisions
  • Data processing impact assessment
  • Security measures implemented
  • Regular compliance reviews
  • User complaints and resolutions related to CAPTCHA

This documentation protects you if a regulator asks questions.

Step 7: Regularly Test and Update Your Implementation

GDPR compliance isn't a one-time achievement. Schedule regular reviews of your CAPTCHA implementation to:

  • Test for unnecessary data collection
  • Verify that retention periods are being respected
  • Ensure privacy notices remain accurate
  • Adapt to evolving regulatory guidance

Essential GDPR Compliance Checklist for CAPTCHA Implementation

Use this checklist to verify your CAPTCHA implementation meets GDPR requirements:

  • [ ] Legal basis clearly established and documented
  • [ ] Privacy policy updated with CAPTCHA-specific information
  • [ ] Data processing agreement in place with CAPTCHA provider
  • [ ] Data minimisation principles applied to collection settings
  • [ ] Appropriate retention periods established and enforced
  • [ ] Accessible alternatives are provided for all users
  • [ ] Data subject rights procedures cover CAPTCHA data
  • [ ] Regular compliance audits scheduled
  • [ ] Staff trained in handling CAPTCHA-related privacy inquiries
  • [ ] Documentation maintained for accountability purposes

Compliance is an ongoing process rather than a one-off task. CAPTCHA technologies and regulators' interpretations both change, so keep up to date and be ready to adapt your implementation.

Code-Level Strategies: Privacy-Focused CAPTCHA Implementation Blueprints

A GDPR-friendly CAPTCHA depends on how it is built, for compliance and for security. Good intentions aren't enough, because the code has to do the right thing.

The examples below show developers how to implement privacy-respecting CAPTCHA solutions.

Configuring reCAPTCHA to Maximize Privacy Protection

Google's reCAPTCHA is everywhere, but its default settings aren't always the best choice for GDPR. Here's how to configure it with privacy in mind:

Use reCAPTCHA v3 with Minimized Data Collection

reCAPTCHA v3 runs invisibly and scores user interactions based on behaviour. For GDPR compliance, what matters is how you implement it:

<!-- Add to your HTML head section -->  
<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY"></script>  

<script>  
  // Only execute reCAPTCHA when absolutely necessary (e.g., form submission)  
  document.getElementById('contact-form').addEventListener('submit', function(event) {  
    event.preventDefault();  
    
    // Execute reCAPTCHA with limited scope  
    grecaptcha.execute('YOUR_SITE_KEY', {action: 'submit_form'})  
    .then(function(token) {  
      // Include token in form submission  
      document.getElementById('g-recaptcha-response').value = token;  
      document.getElementById('contact-form').submit();  
    });  
  });  
</script>

Privacy improvements in this implementation:

  • CAPTCHA only runs when needed (form submission)
  • Limited action scope ('submit_form')
  • No unnecessary page tracking

Self-Hosted CAPTCHA Backend Verification

For maximum data control, implement server-side validation that keeps data sharing to a minimum:

<?php
// Server-side verification with minimal data sharing
function verifyCaptcha($recaptcha_response) {
  // Only necessary parameters sent to Google
  $verification_data = [
    'secret'   => 'YOUR_SECRET_KEY',
    'response' => $recaptcha_response,
    // Deliberately NOT sending user IP - increases privacy
    // 'remoteip' => $_SERVER['REMOTE_ADDR']
  ];

  $options = [
    'http' => [
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($verification_data)
    ]
  ];

  $context = stream_context_create($options);
  $result = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
  $result_data = json_decode($result);

  // Log minimal verification data - exclude user identifiers
  error_log('CAPTCHA verification attempted. Success: ' . ($result_data->success ? 'Yes' : 'No'));

  return $result_data->success && $result_data->score >= 0.5;
}
?>

This approach deliberately does not send the user's IP address to Google, reducing the personal data footprint while maintaining security.

Under GDPR, when using legitimate interest as your legal basis, you still need to be transparent. When using consent as your basis, that consent must be explicit and informed.

Transparent Notification Banner

<div id="captcha-notice" class="privacy-notice">
  <p>
    This form is protected by CAPTCHA technology to prevent spam.
    <strong>When you submit this form</strong>, we'll process limited interaction
    data to verify you're human.
  </p>
  <p>
    See our <a href="/privacy#captcha">Privacy Policy</a> for details on what
    data is processed and how long it's retained.
  </p>
  <button onclick="acknowledgeCaptchaNotice()">I understand</button>
</div>

<script>
  function acknowledgeCaptchaNotice() {
    // Store acknowledgment in localStorage instead of cookies when possible
    localStorage.setItem('captchaNoticeAcknowledged', 'true');
    document.getElementById('captcha-notice').style.display = 'none';
  }

  // Check if user has already acknowledged
  window.addEventListener('DOMContentLoaded', function () {
    if (localStorage.getItem('captchaNoticeAcknowledged') === 'true') {
      document.getElementById('captcha-notice').style.display = 'none';
    }
  });
</script>

This approach clearly informs users before they engage with your CAPTCHA-protected form, supporting transparency requirements.

Where you collect more sensitive data through behaviour analysis:

// More explicit consent approach for higher-risk CAPTCHA implementations
const captchaConsentManager = {
  consentGiven: false,

  initialize: function() {
    // Check for existing consent
    this.consentGiven = localStorage.getItem('captchaConsent') === 'granted';
    this.updateUI();

    // Attach event listeners
    document.getElementById('consent-yes').addEventListener('click', () => this.updateConsent(true));
    document.getElementById('consent-no').addEventListener('click', () => this.updateConsent(false));
  },

  updateConsent: function(consented) {
    this.consentGiven = consented;

    // Record timestamp of consent for audit purposes
    const consentRecord = {
      status: consented ? 'granted' : 'denied',
      timestamp: new Date().toISOString(),
      version: '1.2' // Consent policy version
    };

    // Store in localStorage with expiry (90 days)
    localStorage.setItem('captchaConsent', consented ? 'granted' : 'denied');
    localStorage.setItem('captchaConsentDetails', JSON.stringify(consentRecord));

    this.updateUI();

    // Optional: Send to server for audit trail if needed
    this.logConsentChange(consentRecord);
  },

  updateUI: function() {
    document.getElementById('captcha-consent-banner').style.display =
      this.consentGiven ? 'none' : 'block';

    document.getElementById('submit-button').disabled = !this.consentGiven;
  },

  logConsentChange: function(record) {
    // Send minimized data to server (audit trail)
    fetch('/api/consent-log', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        feature: 'captcha',
        consentStatus: record.status,
        consentVersion: record.version
        // Deliberately NOT sending user identifiers
      })
    });
  }
};

// Initialize consent manager
document.addEventListener('DOMContentLoaded', function() {
  captchaConsentManager.initialize();
});

This implementation creates a documented consent mechanism that records when consent was given and which version of it, which you need for accountability under GDPR.

Server-Side Validation with Minimized Data Collection

Proper server-side validation is crucial for CAPTCHA security, and it can be done while keeping data collection to a minimum:

# Python example using Flask
from flask import Flask, request, jsonify
import requests
import hashlib
from datetime import datetime, timedelta

app = Flask(__name__)

# In-memory temporary store instead of database
# For production, use a database with automatic deletion
temporary_verification_store = {}

@app.route('/verify-captcha', methods=['POST'])
def verify_captcha():
    captcha_response = request.form.get('g-recaptcha-response')
    form_id = request.form.get('form_id')
    
    # Generate anonymous identifier instead of storing user IP
    # This uses a hash of IP + form ID but ONLY stores the hash
    session_now = datetime.now().strftime("%Y-%m-%d-%H")
    anonymous_id = hashlib.sha256(
        f"{request.remote_addr}:{form_id}:{session_now}".encode()
    ).hexdigest()
    
    # Check for too many attempts from same source
    attempts = temporary_verification_store.get(anonymous_id, 0)
    if attempts > 5:
        return jsonify({'success': False, 'error': 'rate_limit'})
    
    # Verify with minimal data sent to CAPTCHA provider
    verification_data = {
        'secret': 'YOUR_SECRET_KEY',
        'response': captcha_response
        # IP not shared with provider
    }
    
    result = requests.post(
        'https://www.google.com/recaptcha/api/siteverify',
        data=verification_data
    ).json()
    
    # Update counter (with auto-expiry logic)
    temporary_verification_store[anonymous_id] = attempts + 1
    
    # Schedule cleanup of old records (every 100 requests)
    if len(temporary_verification_store) % 100 == 0:
        cleanup_old_records()
    
    return jsonify({
        'success': result.get('success', False),
        # Share minimal data with client
        'error': result.get('error-codes', [])[0] if not result.get('success', False) else None
    })

def cleanup_old_records():
    """Remove entries older than 1 hour to minimize data retention"""
    current_hour = datetime.now().strftime("%Y-%m-%d-%H")
    keys_to_remove = []
    
    for key in temporary_verification_store:
        if current_hour not in key:
            keys_to_remove.append(key)
    
    for key in keys_to_remove:
        del temporary_verification_store[key]

This implementation uses several privacy-enhancing techniques:

  • Anonymous request identification
  • Rate limiting without persistent user tracking
  • Minimal data sharing with the CAPTCHA provider
  • Automatic data cleanup

Using localStorage Instead of Cookies Where Possible

Using localStorage does not get round the consent rule. Article 5(3) of the ePrivacy Directive applies to storing or reading any information on the visitor's device, not only cookies, and the European Data Protection Board's guidelines on its technical scope list local storage alongside cookies as information stored on the device. The exemption for storage that is strictly necessary for a service the visitor asked for applies whichever mechanism you use, so assess localStorage exactly as you would a cookie. The example below keeps a short record of verification attempts in localStorage:

// CAPTCHA state management using localStorage instead of cookies
const privacyFriendlyCaptcha = {
  initialize: function() {
    // Check for verification attempts in localStorage
    let attempts = localStorage.getItem('captchaAttempts');
    attempts = attempts ? JSON.parse(attempts) : { count: 0, timestamp: Date.now() };

    // Reset counter if older than 1 hour
    if (Date.now() - attempts.timestamp > 3600000) {
      attempts = { count: 0, timestamp: Date.now() };
    }

    localStorage.setItem('captchaAttempts', JSON.stringify(attempts));

    // Implement progressive difficulty based on attempts
    if (attempts.count > 3) {
      this.loadStrongerCaptcha();
    } else {
      this.loadSimpleCaptcha();
    }
  }

This approach uses progressive security enhancement, which means it only makes the CAPTCHA harder when necessary, and it keeps its state in localStorage, which needs the same consent assessment as a cookie.

Implementing a Custom, Minimal CAPTCHA Solution

For complete control over data processing, you can build a simple CAPTCHA of your own:

// Frontend implementation of minimal CAPTCHA
const simpleCaptcha = {
  challenge: '',

  initialize: function() {
    // Generate random challenge server-side
    fetch('/api/get-captcha-challenge')
      .then(response => response.json())
      .then(data => {
        this.challenge = data.challenge;
        this.displayChallenge(data.display);
      });
  },

  displayChallenge: function(displayData) {
    const container = document.getElementById('captcha-container');
    container.innerHTML = `
      <div class="captcha-challenge">
        <p>${displayData.question}</p>
        <input type="text" id="captcha-answer" aria-label="CAPTCHA answer" />
        <input type="hidden" id="captcha-id" value="${displayData.id}" />
      </div>
    `;
  },

  verify: function() {
    const answer = document.getElementById('captcha-answer').value;
    const id = document.getElementById('captcha-id').value;

    return fetch('/api/verify-captcha', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id, answer })
    })
      .then(response => response.json())
      .then(result => {
        if (result.success) {
          // Clear data after successful verification
          document.getElementById('captcha-answer').value = '';
        } else {
          // Refresh on failure
          this.initialize();
        }
        return result.success;
      });
  }
};

This custom solution shows privacy by design by:

  • Creating verification without third-party services
  • Storing minimal challenge data
  • Implementing automatic data deletion
  • Using simple challenges that don't require behaviour analysis

By following these examples, you can build CAPTCHA systems that balance security needs with GDPR privacy requirements, protecting both your users and your organisation.

Secure Your Forms While Respecting User Privacy Rights

A privacy-first CAPTCHA is essential for protecting user data, avoiding fines, and maintaining trust. By collecting as little data as possible, being transparent and choosing secure solutions, you can balance compliance and security. Regular audits and attention to accessibility make your approach stronger still.

Enhance security and privacy with Prosopo's PoW CAPTCHA - efficient, user-friendly, and built for modern web protection. Get started today!

Bot Protection Without Data Harvesting

A Bot Exposure Assessment is a 30-minute call with an engineer. We look at your traffic, show where your current setup leaves gaps, and agree how a trial would be judged. Nothing to install first.

Questions

Something else? Ask an engineer.

How do you make a CAPTCHA GDPR compliant?

Establish a valid legal basis, update your privacy policy, choose a GDPR-friendly CAPTCHA, collect only the data you need, keep it accessible, document your compliance measures, and test and update the set-up regularly. You also need a data processing agreement with your CAPTCHA provider.

What legal basis can I use for a CAPTCHA under GDPR?

The two most applicable are legitimate interest, meaning protecting your website from spam and bot attacks, and consent. If you rely on legitimate interest, document a legitimate interest assessment showing that your security interests outweigh the possible privacy impact.

What personal data does a CAPTCHA collect?

CAPTCHAs often collect IP addresses, browser information, mouse movements, interaction patterns and cookie data, and sometimes biometric data when they use behavioural analysis. How much each provider collects, and where it is processed, varies.

What should my privacy policy say about a CAPTCHA?

It must say that you use CAPTCHA technology, what data is collected, how long it is kept, the legal basis for processing it, and which third parties, if any, have access to it.

Does storing CAPTCHA data in localStorage instead of cookies avoid the consent rule?

No. Article 5(3) of the ePrivacy Directive applies to storing or reading any information on the visitor's device, not only cookies, and the European Data Protection Board's guidelines list local storage alongside cookies. The exemption for storage that is strictly necessary for a service the visitor asked for applies whichever you use, so assess localStorage exactly as you would a cookie.