Back to Knowledge Hub
Getting Started

Playwright Basic Auth: 401 Loop, Popup and Credentials

Separate a missing HTTP challenge from a login form or routed response. Use a local 401 fixture to show where Playwright sends credentials and where it cannot.

BotBrowser Team

Documentation

Want the structured docs for Getting Started?

This article lives in the editorial library. For step-by-step setup, reference material, and ongoing updates, jump into the docs section.

The owned local origin challenges once, accepts a credential-bearing retry, and never sees a route-fulfilled request.

HTTP Basic authentication starts with a challenge. A navigation without credentials receives 401 plus WWW-Authenticate, and the browser may retry with an Authorization header if the context has matching httpCredentials. A page-side fetch in the same context can ride that same credential path once the origin has been challenged. A route that fulfils locally never asks the origin, so no credential exchange happens at all. BotBrowser can keep a profile-backed Chromium environment consistent while these cases are repeated, but it does not store credentials, answer an origin challenge or authenticate an application login form.

This distinction decides what a timeout means. A missing challenge cannot be repaired by a credential object, and a rejected challenge is not a reason to keep pressing a visible login button. Read the first exchange and name which component owns the decision before changing a launch option.

TL;DR

  • httpCredentials is context configuration for HTTP authentication. It is not a universal header injector and it does not replace an application login form.
  • The document navigation drew one unauthenticated request and one authenticated retry, and the page fetch went out already authorized; the fulfilled route path made no origin request.
  • The absent origin challenge is the first useful observation. A credential object cannot turn a plain 200, a redirected login page or a locally fulfilled response into an HTTP-auth exchange.
  • The first failed request can look like a timeout because the browser, a route handler or the application is waiting at a different layer. Preserve the request URL, response status, WWW-Authenticate header and browser error.
  • httpCredentials.origin limits which origin may receive the context's credentials. It does not authorize the request or make the server accept the pair.
  • BotBrowser keeps browser and profile inputs explicit for repeatable tests; it does not store credentials or skip origin authentication.

Table of contents

The Playwright proxy configuration article owns proxy routes and 407 challenges. An origin 401 belongs here, and the Puppeteer proxy authentication comparison keeps the same origin-versus-proxy split for another automation library.

Find the first authentication challenge

Start with the request that arrived before any retry. In the owned run, the first navigation had no Authorization header and the origin returned 401 with a Basic challenge. The browser then repeated the request with credentials from httpCredentials. That sequence is the HTTP authentication contract; it is not evidence that the application has a password field or a session cookie.

The initial request matters because a credential-bearing retry can hide the reason the first one was rejected. If a test records only the final 200, it cannot distinguish a real HTTP-auth exchange from a route that manufactured a success response. If it records only page.goto: Timeout, it cannot distinguish an absent challenge from a slow application, a redirect loop or a blocked request.

The MDN HTTP authentication guide describes a server challenge and a client credential response. The Playwright BrowserContext reference documents httpCredentials as credentials for HTTP authentication, with an optional exact origin and a send option scoped to API requests from a corresponding APIRequestContext. The last scope is easy to miss: the browser requests in this fixture are governed by the browser context, not by the API request setting.

For an owned fixture, the smallest useful record has five fields:

RecordWhat to preserveWhat it rules out
Request URLFull scheme, host and portA different origin receiving the credentials
First responseStatus and WWW-Authenticate headerA route response or an application login page
Retry requestWhether Authorization is present and matches the expected challengeA credential object that never entered the browser path
Browser errorpage.goto or fetch rejection textA timeout with no known terminal state
Context configurationhttpCredentials.origin and the shape of the credential objectSending credentials to every origin

The table is a diagnostic order. Read the first response before looking at the final page, then read the retry before assuming the server accepted the pair. A 200 after a challenge establishes an HTTP-auth exchange for that request. It does not establish that an application session, a role or a durable account exists.

Read the three outcomes from one owned origin

The fixture used one loopback origin on 127.0.0.1, a context-level credential object, and an installed stock Chrome build. The run executed three owned cases one after another and requested a pool of three; the effective pool was three because the case count was three. No third-party request was made.

The origin's counter recorded the shape of each request rather than storing the shared secret in the report. For the navigation case, the first request was unauthenticated, the retry matched the expected Basic value, and the page-side fetch to the same origin went out already authorized, without a new origin 401. A context-level route then fulfilled a separate path locally; that request never reached the origin and produced no credential exchange there.

The measured record from docs/evidence/playwright-basic-auth-popup-and-http-credentials-run-20261125.json is:

Controlled caseOrigin-visible sequenceFinal observation
Navigation401 without Authorization, then 200 with matching credentialsDocument marker rendered
Page fetch200 on the first attempt, already authorizedJSON body {"value":"page-fetch-ok"}
Route-fulfilled pathThe fulfilled request never reached the originJSON body {"value":"route-ok"}, one route fulfillment

Those three rows answer different questions. The first proves the navigation entered the HTTP-auth path. The second shows that a page-side fetch is not necessarily exempt from that path; in this run it carried credentials on its first attempt, after the document exchange had already challenged the origin. The third proves that a route can answer a request without any origin challenge, so "authentication succeeded" is not a valid interpretation of its 200.

The run's browser build was Chrome 158.0.8127.89. All three cases reported passed, with the same browser version in each case. The evidence file retains the request counts, whether an Authorization header was present, whether it matched, and the final response bodies. The fixture source is beside the evidence so a reviewer can inspect the counters rather than reconstructing a claim from prose. The fixture prints its run record to stdout when it finishes; the routed-path case line in that output is:

"case": "route-fulfilled-no-credential-exchange",
const context = await browser.newContext({
  httpCredentials: {
    username: 'owned-user',
    password: 'owned-pass',
    origin: `http://${originHost}`,
  },
});

const page = await context.newPage();
const response = await page.goto(`http://${originHost}/`);
if (response.status() !== 200) throw new Error('Expected an authorized navigation');

const result = await page.evaluate(async url => {
  const reply = await fetch(url);
  return { status: reply.status, body: await reply.text() };
}, '/page.json');

This snippet is a shape, not a credential policy. Replace the placeholders with an owned origin. Keep the expected status and the challenge header in a record beside the output. If the first request never receives a 401, adding a second credential object cannot create a challenge that the origin did not send.

A 200 from route.fulfill is not authentication

A locally fulfilled response can be useful for a page that must render without a live origin, but it removes the credential exchange being investigated. In the fixture, the route returned {"value":"route-ok"} and its counter was the only evidence that a response was fabricated locally. The fulfilled request never reached the origin. A test that expects an Authorization header on that route has made a false assumption about which layer receives the request.

The positive version of the route case is explicit: use it to isolate page behavior from a dependent service, label it as synthetic, and assert the synthetic response separately from any origin-auth result. The network mocking for owned tests article owns the general test-double decision. The route case only names the moment the route removes an authentication observation.

Choose context credentials, a request header or an application login

The question "playwright basic auth" is too broad to answer with one option because three different layers share a 401-shaped symptom.

Failure surfaceWhere the decision livesSafe next observation
Browser receives an HTTP 401 and retriesBrowserContext's HTTP-auth configurationFirst request has no header; retry has a matching header
A page API call needs a bearer or custom headerThe page's request code or an explicit request contextThe request body and response are captured independently
A rendered login form asks for a sessionThe application and its server, not HTTP Basic authForm fields, cookies and application state are separate evidence
A route returns a synthetic responseThe test or harness routeOrigin counter is zero; response is labelled synthetic
A 407 appears before the originThe proxy layerProxy challenge and forward count are separate from origin status

The first row is not a recommendation to put credentials in every request. The context option carries the exchange after a challenge; a test that wants a specific header on an application API should state that contract and keep the header out of logs. The third row is the most common wrong turn: an HTML form with username and password fields is not HTTP Basic auth merely because it shows the same words.

send: "always" also needs careful reading. The API reference says it applies to requests from a corresponding APIRequestContext and does not affect requests sent from the browser. Do not set it on a browser context and assume a page-side fetch() now sends an Authorization header on every request. In the owned run, the page-side fetch succeeded because the context credential applied to that origin after the document challenge, not because send: "always" was active.

Use the same rule for an explicit header. If an application requires a bearer token, set that contract in the page request or a dedicated request client; do not forward a browser Basic credential object as a substitute. The Playwright browser setup page covers the context and browser ownership around such a test. The fixture above covers the moment the origin challenges the browser.

Why the popup can look like a hang

A browser-driven HTTP challenge commonly appears in a headed browser and can be handled automatically when httpCredentials is present. In a scripted run, the first 401 may be followed by a retry that never completes, or by a page that changes to a login screen. Both can surface as a navigation timeout. The timeout is the terminal symptom; the failure can sit in the browser, a route handler or the application.

Record the response from page.goto() when it exists, then the request events and the first document state. If the first response is 401 and the retry lacks credentials, the context does not cover that origin. If the first response is a redirect to an HTML login page, the server is asking for an application session and httpCredentials will not fill it. If the origin returns a different challenge scheme, the Basic pair is not a universal answer. The self-signed certificate error diagnosis handles a different connection-level failure that can also produce an unhelpful navigation symptom.

Keep the fixture and the evidence safe

The owned fixture uses 127.0.0.1, a temporary port and a throwaway username/password pair. It makes no request to a third-party service and emits no credential in the report. The request count uses the presence and match of an Authorization header, not the raw header. A reviewer can confirm the exchange without copying a secret into a blog, an issue or a chat thread.

The fixture is not a recommendation to publish credentials in source. The fixed pair exists only for a loopback test. In a real test, load secrets from a test-only provider, restrict the origin, and keep the credential out of traces, screenshots and assertion messages. If a failed test logs the request, redact the header before sharing the output. HTTP Basic is not a way to send an application login; its confidentiality on the wire depends on transport security, and a local HTTP fixture does not model that production condition.

The first 401 and the retry should stay in the same evidence record. A reviewer who sees only the final 200 cannot tell whether a route fabricated it, an origin accepted the credential, or a redirect reached an unrelated app. The next run must repeat the same origin, the same expected credential and the same route condition. A different port or a different credential pair is a different experiment.

BotBrowser capability and limitation

BotBrowser's Playwright setup documents an explicit Chromium executable and profile for Playwright launches. That keeps the browser and profile inputs stable while a test compares the three cases, so a changed response is less likely to come from a drifting browser environment. The BotBrowser browser overview describes the profile-backed surfaces that the test can hold fixed; the Playwright BrowserContext reference documents where origin HTTP credentials belong.

The limitation sits in the same paragraph: BotBrowser does not store or inject HTTP credentials, does not answer a 401 challenge for an arbitrary site, and does not skip origin authentication. The test code must supply the credential context and the application must accept it. A profile can make the browser environment repeatable; it cannot make a missing challenge appear or turn a login form into HTTP Basic auth.

FAQ

Does httpCredentials work for page-side fetch?

In the owned run it did. The document navigation completed the 401 exchange, and the page-side fetch to the same origin went out already authorized on its first attempt, returning 200 without a new origin 401. That result belongs to the tested Chrome build and context; do not transfer it to an API that requires a bearer token or to an HTML login form.

Is a 200 enough to prove authentication?

No. Record the first 401 challenge and the Authorization-bearing retry. A route-fulfilled 200 has no origin request, and an application page can return 200 with a login form. The status alone does not identify the layer.

How do I scope credentials to one origin?

Set httpCredentials.origin to the exact scheme, host and port. In the fixture the context used one loopback origin, so a request to a different origin was not covered. Remove the shared secret from the report and assert the matching header without printing it.

Why is a login popup not fixed by httpCredentials?

A popup or form is an application interface, while httpCredentials is for the HTTP authentication challenge. If the server returns an HTML login page rather than a 401 with a supported challenge, the application session is the layer that must handle the login.

What should I check before increasing a timeout?

Check the first response status, the challenge header, whether the retry carried a matching Authorization header, and whether a route handled the request. If none of those exists, the timeout is not telling you that the credential pair was wrong.

Sources

Practical conclusion

The first authentication challenge is the boundary. An origin that returns 401 plus a supported challenge can cause the browser to retry with matching context credentials. A page-side fetch can enter that same browser-auth path, but the test must observe the first response and the retry rather than infer them from a final body. A route-fulfilled 200 never reached the origin, and an application login page belongs to a different component. BotBrowser can keep the browser environment steady; it cannot create the challenge, store the credentials or authorize the origin. Preserve the first exchange, then choose the layer that actually owns the failure.

#Playwright Basic Auth#httpCredentials#401#Authentication#Test Diagnostics

This article is part of the guide: Browser Automation Getting Started: A First Run Map

Run the same check in BotBrowser

Load a profile, keep the signals you just read about consistent inside the browser, and confirm the result on your own machine before a rollout.