Pass HTTP basic authentication

Set httpCredentials as a context option so protected pages load without a browser prompt.

A page behind HTTP basic auth answers with 401 until the request carries an Authorization header. The browser would normally show a native username and password prompt, which Playwright cannot type into. Set httpCredentials as a context option instead, and every request from that context sends the header for you.

Set credentials on the context

Pass httpCredentials inside the context key of Playwright::chromium(). The top level of the options array configures the browser launch; the context key configures the browser context, and the credentials belong there.

php
$password = getenv('STAGING_PASSWORD');

if (false === $password || '' === $password) {
    throw new RuntimeException('STAGING_PASSWORD is required');
}

$context = Playwright::chromium([
    'context' => [
        'httpCredentials' => [
            'username' => 'staging',
            'password' => $password,
        ],
    ],
]);

$page = $context->newPage();
$page->goto('https://staging.example.test/');

expect($page->getByRole('heading', ['name' => 'Dashboard']))->toBeVisible();

The context forwards httpCredentials to the browser context, so the header is attached before the first navigation. No prompt appears.

Keep the password out of the source

Read the password from the environment rather than hard-coding it. Stop before launching when CI did not provide the secret; an empty password turns a configuration error into a confusing 401.

Do not put credentials in the URL. URLs are routinely copied into logs, screenshots, and failure output.

Expected result

The protected page loads directly and the browser does not show a native credentials prompt. Assert a user-visible element from the authenticated page, such as a dashboard heading.

Go next

← All recipes