MODIFYING REQUEST & RESPONSE HEADERS

Master HTTP header manipulation in Playwright with Python: global extra_http_headers, route.continue_ mutations, injecting Authorization Bearer tokens, stripping CORS restrictions, CSP overrides, and inspecting upstream response headers.

πŸ“‘ Why Mutate HTTP Headers in Automated Tests?

HTTP headers govern the security, caching, encoding, and authentication layers of modern web architecture. During end-to-end testing, engineers frequently need to bypass basic authentication barriers, supply signed JSON Web Tokens (JWT), inject correlation tracing IDs (such as X-Correlation-ID), emulate international locales via Accept-Language, or temporarily disable restrictive Content Security Policy (CSP) and Cross-Origin Resource Sharing (CORS) response headers to facilitate testing. Playwright provides two primary paradigms for header control: static session-wide injection through extra_http_headers on the BrowserContext, and dynamic in-flight mutation using route handlers via route.continue_(headers=...) and route.fulfill(response=..., headers=...).

1. Static vs. Dynamic Header Modification Strategies
Playwright allows applying headers either globally to every outgoing network request across an entire browser context or conditionally to targeted endpoints via granular route interceptors.
Header Strategy Topology
APPROACH 1: STATIC CONTEXT-WIDE HEADERS (extra_http_headers)
[ browser.new_context(extra_http_headers={"Authorization": "Bearer ..."}) ]
         β”‚
         β”œβ”€β”€ Appended automatically to every request (HTML, CSS, Fetch, API)
         └── Best for: API keys, static staging auth flags, custom User-Agents

APPROACH 2: DYNAMIC IN-FLIGHT ROUTE MUTATION (route.continue_ / route.fulfill)
[ page.route("**/api/v1/orders/*", handler) ]
         β”‚
         β”œβ”€β”€ Intercepts targeted outbound request
         β”œβ”€β”€ Reads live headers: req_headers = route.request.headers
         β”œβ”€β”€ Mutates or deletes keys: req_headers["X-Trace-ID"] = "TR-9901"
         └── Forwards to live upstream server: route.continue_(headers=req_headers)
Engineering Rule: Use extra_http_headers for uniform credentials across the suite; use route handlers when mutating conditional headers or rewriting response headers.
Real-Time Example 1: Global Session Headers via context.set_extra_http_headers()
Configure global custom HTTP headers on context creation or update them dynamically across all open tabs using context.set_extra_http_headers().
Python (Global extra_http_headers Setup)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    # 1. Initialize context with global default headers
    context = browser.new_context(
        extra_http_headers={
            "X-QA-Automation-Framework": "Playwright-Python",
            "X-Environment-Cluster": "Staging-Pune-DC"
        }
    )

    page = context.new_page()
    page.goto("https://httpbin.org/headers")

    print("Initial Global Headers Verified on Remote Server:")
    initial_dump = page.inner_text("pre")
    for line in initial_dump.splitlines():
        if "X-Qa-Automation" in line or "X-Environment" in line:
            print(" ", line.strip())

    # 2. Update headers dynamically across all pages in the context
    context.set_extra_http_headers({
        "X-QA-Automation-Framework": "Playwright-Python",
        "X-Environment-Cluster": "Staging-Pune-DC",
        "X-User-Role": "Auditor"
    })

    page.reload()
    print("Updated Headers After set_extra_http_headers():")
    updated_dump = page.inner_text("pre")
    for line in updated_dump.splitlines():
        if "X-User-Role" in line:
            print(" ", line.strip())

    context.close()
    browser.close()
Output: Initial Global Headers Verified on Remote Server: "X-Environment-Cluster": "Staging-Pune-DC", "X-Qa-Automation-Framework": "Playwright-Python" Updated Headers After set_extra_http_headers(): "X-User-Role": "Auditor"
Real-Time Example 2: In-Flight Outbound Header Mutation via route.continue_()
Intercept specific outgoing requests, copy their current headers dictionary, append dynamic values (such as timestamped tokens or correlation IDs), and forward them to the live server.
Python (route.continue_ Header Mutation)
import time
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    def intercept_and_stamp_headers(route):
        # Extract live request headers
        headers = route.request.headers
        
        # Inject dynamic correlation and timestamp headers
        headers["X-Correlation-ID"] = f"CID-{int(time.time() * 1000)}"
        headers["X-Client-App"] = "Nikita-QA-Automation-Engine"
        
        # Forward request to actual live server with mutated headers
        route.continue_(headers=headers)

    # Route only calls targeted to /headers endpoint
    page.route("**/headers", intercept_and_stamp_headers)

    page.goto("https://httpbin.org/headers")
    response_body = page.inner_text("pre")

    print("Live Server Received Modified Outbound Headers:")
    for line in response_body.splitlines():
        if "X-Correlation-Id" in line or "X-Client-App" in line:
            print(" ", line.strip())

    browser.close()
Output: Live Server Received Modified Outbound Headers: "X-Client-App": "Nikita-QA-Automation-Engine", "X-Correlation-Id": "CID-1730177000123"
Real-Time Example 3: Injecting Authorization Bearer Tokens into API Requests
Bypass interactive user interface login screens for data setup by injecting a mock or pre-generated OAuth2 Authorization: Bearer <token> header into outgoing API queries.
Python (JWT Bearer Token Injection)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    mock_jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDNxd53u1730177000"

    def inject_bearer_token(route):
        headers = route.request.headers
        headers["Authorization"] = f"Bearer {mock_jwt}"
        route.continue_(headers=headers)

    page.route("**/api/v2/secure-ledger", inject_bearer_token)

    page.set_content("""
        
        Idle
    """)

    # Verify intercepted request contains the injected Bearer header
    with page.expect_request("**/api/v2/secure-ledger") as req_info:
        page.locator("#fetch-btn").click()

    captured_request = req_info.value
    auth_header = captured_request.headers.get("authorization")

    print(f"Captured Outbound Authorization Header:")
    print(f"  Header Value: '{auth_header}'")
    assert auth_header == f"Bearer {mock_jwt}"
    print("JWT Bearer token successfully verified in transit!")

    browser.close()
Output: Captured Outbound Authorization Header: Header Value: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDNxd53u1730177000' JWT Bearer token successfully verified in transit!
Real-Time Example 4: Stripping CORS Headers on Inbound Responses
When automating against disparate cross-origin development backends, bypass browser CORS enforcement by modifying the incoming response headers to include permissive Access-Control-Allow-Origin: *.
Python (Response CORS Header Rewriting)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    def make_permissive_cors(route):
        # 1. Fetch the real response from the upstream server
        response = route.fetch()
        
        # 2. Extract and modify inbound response headers
        headers = response.headers
        headers["access-control-allow-origin"] = "*"
        headers["access-control-allow-methods"] = "GET, POST, PUT, DELETE, OPTIONS"
        headers["access-control-allow-headers"] = "*"

        # 3. Fulfill the response back to browser with permissive CORS
        route.fulfill(
            response=response,
            headers=headers
        )

    page.route("**/api/cross-domain/*", make_permissive_cors)

    page.goto("https://example.com")
    print("CORS response headers successfully rewritten for cross-origin testing.")

    browser.close()
Output: CORS response headers successfully rewritten for cross-origin testing.
Real-Time Example 5: Overriding Content Security Policy (CSP) Headers
Strict Content Security Policy (CSP) headers block injected test scripts or third-party iframe embeds. Strip or loosen content-security-policy response headers during automated test runs.
Python (Bypassing CSP via Response Header Deletion)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    def strip_csp_headers(route):
        # Fetch original response from upstream
        response = route.fetch()
        headers = response.headers

        # Delete CSP restrictions from the response dictionary
        if "content-security-policy" in headers:
            del headers["content-security-policy"]
        if "content-security-policy-report-only" in headers:
            del headers["content-security-policy-report-only"]

        # Fulfill without strict CSP
        route.fulfill(response=response, headers=headers)

    page.route("**/*", strip_csp_headers)

    page.goto("https://example.com")
    print("Content-Security-Policy headers stripped; custom script injection permitted.")

    browser.close()
Output: Content-Security-Policy headers stripped; custom script injection permitted.
Real-Time Example 6: Emulating International Locales via Accept-Language
Test localized international content rendering (e.g., verifying INR currency formatting and regional date structures) by configuring the Accept-Language HTTP header.
Python (Accept-Language Emulation)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    # Configure context with Hindi (India) locale and language preference
    context = browser.new_context(
        locale="hi-IN",
        extra_http_headers={
            "Accept-Language": "hi-IN,hi;q=0.9,en-US;q=0.8,en;q=0.7"
        }
    )

    page = context.new_page()
    page.goto("https://httpbin.org/headers")

    response_text = page.inner_text("pre")
    print("Server Confirmed Inbound Accept-Language:")
    for line in response_text.splitlines():
        if "Accept-Language" in line:
            print(" ", line.strip())

    context.close()
    browser.close()
Output: Server Confirmed Inbound Accept-Language: "Accept-Language": "hi-IN,hi;q=0.9,en-US;q=0.8,en;q=0.7"
Real-Time Example 7: Inspecting All Response Headers & all_headers()
Extract and audit all headers returned by the serverβ€”including security headers like Strict-Transport-Security (HSTS) and caching tokens like ETagβ€”using response.all_headers().
Python (Response Header Audit)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Navigate and capture main document response object
    response = page.goto("https://example.com")

    # all_headers() returns dictionary with lower-cased header keys
    all_hdrs = response.all_headers()

    print(f"Total Response Headers Extracted: {len(all_hdrs)}")
    print("Sample Security & Caching Headers:")
    print(f"  Content-Type : {all_hdrs.get('content-type')}")
    print(f"  Server       : {all_hdrs.get('server')}")
    print(f"  ETag         : {all_hdrs.get('etag')}")
    print(f"  Cache-Control: {all_hdrs.get('cache-control')}")

    browser.close()
Output: Total Response Headers Extracted: 7 Sample Security & Caching Headers: Content-Type : text/html; charset=UTF-8 Server : ECS (dcb/7F3B) ETag : "3147526947+gzip" Cache-Control: max-age=604800
Real-Time Example 8: Handling Case Sensitivity in HTTP Headers
Under HTTP/2 and HTTP/3 specifications, header keys are strictly lowercased. Playwright standardizes request.headers and response.all_headers() to lowercase keys for reliable cross-protocol lookups.
Python (Case Sensitivity Normalization)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Route interceptor checking lowercase keys
    def safe_header_inspector(route):
        headers = route.request.headers
        # Playwright normalizes keys to lowercase
        auth_val = headers.get("authorization") or headers.get("Authorization")
        print(f"Normalized Header Lookup (authorization): '{auth_val}'")
        route.continue_()

    page.route("**/headers", safe_header_inspector)

    page.set_extra_http_headers({"Authorization": "Bearer TOKEN_ABC_9921"})
    page.goto("https://httpbin.org/headers")

    browser.close()
Output: Normalized Header Lookup (authorization): 'Bearer TOKEN_ABC_9921'
Real-Time Example 9: Header Modification Methods Reference Matrix
A comprehensive reference summary of all core methods, signatures, and dictionaries used for inspecting, setting, and mutating HTTP headers in Playwright Python.
Header Methods Reference Matrix
PLAYWRIGHT HTTP HEADERS API MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Method / Property            β”‚ Return Type / Arguments      β”‚ Description / Primary Use Case                          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ extra_http_headers           β”‚ Dict[str, str] (Context Arg) β”‚ Sets global headers applied to every request in context.β”‚
β”‚ context.set_extra_http_...() β”‚ headers: Dict[str, str]      β”‚ Updates global headers dynamically on active context.   β”‚
β”‚ page.set_extra_http_...()    β”‚ headers: Dict[str, str]      β”‚ Updates global headers dynamically on specific page.    β”‚
β”‚ request.headers              β”‚ Dict[str, str] (lowercase)   β”‚ Returns all request headers sent by browser.            β”‚
β”‚ request.header_value(name)   β”‚ str / None                   β”‚ Returns specific request header value by case-ins. name.β”‚
β”‚ response.all_headers()       β”‚ Dict[str, str] (lowercase)   β”‚ Returns all response headers returned by server.        β”‚
β”‚ response.header_value(name)  β”‚ str / None                   β”‚ Returns specific response header value.                 β”‚
β”‚ route.continue_(headers=...) β”‚ headers: Dict[str, str]      β”‚ Overrides outbound request headers sent upstream.       β”‚
β”‚ route.fulfill(headers=...)   β”‚ headers: Dict[str, str]      β”‚ Sets custom inbound response headers returned to client.β”‚
β”‚ route.fetch()                β”‚ kwargs                       β”‚ Fetches real upstream response to read/modify headers.  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Rely on context.set_extra_http_headers() for global authentication tokens and tracing IDs. Use route.continue_(headers=...) when mutating headers conditionally per endpoint.