Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Send a HEAD request in Playwright with APIRequestContext.head(url). It returns an APIResponse containing the status, headers, URL, and other response metadata without downloading the representation body. Use page.request or browserContext.request when the request must share that browser context’s cookies; use playwright.request.newContext() for isolated cookie storage.

The method has been available since Playwright v1.16. The official API reference is at playwright.dev/docs/api/class-apirequestcontext.

What a Playwright HEAD request does

HTTP HEAD asks a server for the metadata it would return for a corresponding GET request, but not the representation body. It is useful for checking whether a resource exists, inspecting cache and content headers, validating redirects, or confirming that an authenticated session can reach an endpoint without transferring the full file.

Playwright exposes this operation on APIRequestContext:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
const response = await request.head('https://example.com/resource');
console.log(response.status());

The returned value is an APIResponse. The target server still decides whether HEAD is supported and which status and headers it returns. A URL that works with GET is not guaranteed to implement HEAD correctly.

Choose the right API request context

Share a browser context’s cookies

page.request and browserContext.request use the APIRequestContext associated with that browser context. Cookies supplied by the context are sent with the request, and cookies set by the response can update the context’s cookie jar. This is the appropriate choice when a page has already logged in or established a session that the HEAD request must reuse.

import { test, expect } from '@playwright/test';

test('checks an authenticated resource', async ({ page }) => {
  const response = await page.request.head('https://example.com/private/report');
  expect(response.ok()).toBeTruthy();
});

You can also obtain the request context from a browser context:

const response = await browserContext.request.head('https://example.com/resource');

Use isolated cookie storage

Create a standalone context when the call should not see or modify browser-session cookies. This is useful for a public-resource check, a separate identity, or tests that must be independent of UI state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { request } from '@playwright/test';

const api = await request.newContext();
try {
  const response = await api.head('https://example.com/resource');
  console.log(response.status());
} finally {
  await api.dispose();
}

With the Playwright library rather than the test fixture, the equivalent setup is await playwright.request.newContext(). Dispose a standalone context when the work is complete.

Complete JavaScript and TypeScript examples

Minimal request

import { request } from '@playwright/test';

const api = await request.newContext();
try {
  const response = await api.head('https://example.com/resource');
  console.log('status:', response.status());
  console.log('content type:', response.headers()['content-type']);
  console.log('content length:', response.headers()['content-length']);
} finally {
  await api.dispose();
}

For TypeScript, the same code is valid. If you need the response object’s type in a helper, import APIResponse from @playwright/test or playwright, matching the package you use.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Check success explicitly

import { request } from '@playwright/test';

const api = await request.newContext();
try {
  const response = await api.head('https://example.com/resource');
  if (!response.ok()) {
    throw new Error(`HEAD failed with HTTP ${response.status()}`);
  }
  console.log(response.url());
} finally {
  await api.dispose();
}

failOnStatusCode is false by default, so a 404 or 500 normally produces an APIResponse instead of throwing solely because of the HTTP status. This lets a test assert the exact status. Set the option to true when non-success responses should raise an exception.

Use headers and query parameters

const response = await api.head('https://example.com/resource', {
  headers: {
    Authorization: `Bearer ${process.env.API_TOKEN}`,
    'X-Test-Run': 'head-check'
  },
  params: {
    version: 'latest',
    region: 'us'
  }
});

params appends query parameters to the URL. Use headers for authorization, content negotiation, tracing, or another server-defined request header. Do not log bearer tokens or session cookies.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Redirects, timeouts, and status handling

Redirect behavior

Playwright follows redirects automatically by default. The documented default maximum is 20 redirects. Set maxRedirects: 0 to inspect the first response without following it, or choose another limit:

const response = await api.head('https://example.com/old-path', {
  maxRedirects: 0
});
console.log(response.status());
console.log(response.headers()['location']);

When redirects are followed, inspect response.url() to see the final URL. A redirect chain can change the host, authentication requirements, or the response headers you are testing.

Timeouts

The request timeout is measured in milliseconds and defaults to 30,000 ms. Set a suitable value for your endpoint, or use timeout: 0 to disable the request timeout:

const response = await api.head('https://example.com/slow-resource', {
  timeout: 10_000
});

An unlimited timeout can leave a test or worker waiting indefinitely if a server never completes the request, so use it only when an outer timeout controls the operation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Read response metadata

const response = await api.head('https://example.com/resource');

console.log({
  status: response.status(),
  statusText: response.statusText(),
  url: response.url(),
  headers: response.headers(),
  server: response.headers()['server']
});

Headers are returned as a name-to-value object. Header names are case-insensitive on the wire; use the normalized lowercase keys returned by Playwright when looking up common fields.

Python: send a HEAD request

The Python API spells the method api_request_context.head(url). A synchronous example is:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    api = p.request.new_context()
    try:
        response = api.head("https://example.com/resource")
        print(response.status)
        print(response.headers)
    finally:
        api.dispose()

The asynchronous API follows the same model:

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        api = await p.request.new_context()
        try:
            response = await api.head("https://example.com/resource")
            print(response.status)
            print(response.headers)
        finally:
            await api.dispose()

asyncio.run(main())

Python options correspond to the same request settings: pass a dictionary containing keys such as headers, params, max_redirects, timeout, and fail_on_status_code according to the Python API’s naming conventions.

Cookie-sharing example with a logged-in page

When a browser page establishes a session, call HEAD through that page’s request context:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { test, expect } from '@playwright/test';

test('uses the page session for a HEAD check', async ({ page }) => {
  await page.goto('https://example.com/login');
  await page.getByLabel('Email').fill(process.env.TEST_EMAIL!);
  await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();

  const response = await page.request.head('https://example.com/account/export');
  expect(response.status()).toBe(200);
});

The request context associated with the browser context carries the session cookies. A standalone context created with request.newContext() does not automatically inherit them.

Common problems and fixes

The server returns 405 Method Not Allowed

The endpoint may not support HEAD, or may permit it only on a different route. Confirm the API documentation and test the endpoint’s documented behavior. Do not silently replace HEAD with GET if avoiding the body is the reason for the check.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The result is 401 or 403

Use page.request or browserContext.request when authentication was established in that browser context. For token-based APIs, pass the required Authorization header. Check that a redirect did not send the request to a host where the credentials are not valid.

A redirect hides the original status

Set maxRedirects: 0 and inspect the location header. If you need the final resource, retain the default behavior and assert response.url() as well as the final status.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The request times out

Investigate DNS, TLS, proxy, server latency, and network-idle behavior independently of the browser page. Increase the millisecond timeout only when the endpoint legitimately needs more time; otherwise fix the underlying availability problem.

failOnStatusCode throws unexpectedly

Leave it false while testing expected 3xx, 4xx, or 5xx outcomes and assert response.status() yourself. Set it true only when any non-success status is an error for the test.

Headers differ from a browser navigation

An API request is not a full page navigation. If server behavior depends on cookies, authorization, user agent, or another header, configure that value explicitly or use the browser-context request object that supplies the required cookie jar.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Reliability and test-design guidance

  • Assert the exact status when the distinction matters; use response.ok() for a broad successful-status check.
  • Record the final URL when redirects are allowed.
  • Check the specific headers your application relies on, such as content-type, etag, last-modified, or content-length, but allow for servers that omit or calculate them differently for HEAD.
  • Use isolated contexts in parallel tests when shared cookies could create order-dependent results.
  • Dispose contexts created by newContext() so sockets and resources are released.
  • Keep credentials in environment variables or Playwright project configuration rather than source code.

Because HEAD omits the representation body, it can reduce transfer for large resources, but it does not guarantee a cheap server-side operation. The origin may still perform much of the same work as GET, and intermediary caches or proxies can produce different behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

If your actual goal is a clean visual capture rather than HTTP metadata, ScreenshotNeo provides a one-call screenshot API at screenshotneo.com. Its API can accept a URL directly, so there is no Playwright browser project to install or maintain.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the complete parameter reference in the ScreenshotNeo documentation. ScreenshotNeo removes cookie-consent banners, newsletter popups, and chat widgets before capture. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and each response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers. It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account to try it.

Frequently asked questions

Does Playwright download a response body for HEAD?

No. HEAD requests ask for response metadata without the representation body, although server and proxy behavior can vary.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I use HEAD with a page URL?

Yes, but call it through an APIRequestContext; page.goto() performs navigation rather than exposing a HEAD-specific navigation API.

What is the default redirect limit?

Playwright follows redirects automatically and documents a default maximum of 20. Configure maxRedirects when that behavior is not appropriate.

When should I avoid sharing cookies?

Use a standalone request context when the check must be unauthenticated or isolated from the browser session.

Frequently Asked Questions

Can a HEAD request set cookies?

Yes. When the request uses the APIRequestContext associated with a browser context, cookies from the response can update that context’s cookie storage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I prevent redirects entirely?

Pass maxRedirects: 0 to head() and inspect the returned status and location header.

What does response.ok() mean?

It reports whether Playwright considers the HTTP response successful; use response.status() when your test needs an exact code.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.