How to Test a Basic-Auth-Protected Page with Playwright
If you add httpCredentials to use in the Playwright config file, you can open a Basic-auth-protected page without writing any authentication code in the test. This setting is useful when you want to run E2E tests against a staging environment or a site not yet public that is still behind Basic authentication.
In my test environment, a page that returned 401 without credentials opened with 200 once httpCredentials was set. I also recorded the requests that reached the server, to confirm when the credentials are sent and to which origin.
The test environment was Ubuntu 24.04, Node.js 22.23.5, @playwright/test 1.63.0, and TypeScript 5.9.3. I ran tests only with Chromium (headless). The Basic auth server was built with Node.js's http module and ran on ports 3000 and 3001 on localhost. The username and password were test values I made up. I did not test Firefox or WebKit, an HTTPS server, or a page that logs in with a form.
- 1. Without credentials, you get 401
- 2. Opening the page with httpCredentials in the config file
- 3. Specifying origin to limit which server receives the credentials
- 4. When using different users per origin, wrap the array one more level
- 5. Setting credentials partway through a test
- 6. For API tests, send: 'always' sends credentials from the first request
Without credentials, you get 401
The server used in the test returns 200 with an "admin" page when the username and password in the Authorization header match. When they don't match, it returns 401 with WWW-Authenticate: Basic realm="staging". I set it up to write each received request to server.log, one line each, with the port, path, username sent, and status code returned.
// server.mjs (excerpt)
const users = { 3000: ['tester', 's3cret'], 3001: ['viewer', 'v1ewer'] };
// …
const status = ok ? 200 : 401;
appendFileSync('server.log', `port=${port} ${req.method} ${req.url} auth=${got} -> ${status}\n`);
if (!ok) {
res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="staging"', 'Content-Type': 'text/html; charset=utf-8' });
res.end('<h1>401 Unauthorized</h1>');
return;
}
First, I ran a test that opens a page without any setting.
// tests/no-auth/page.spec.ts
import { test, expect } from '@playwright/test';
test('認証情報なしでは 401 になる', async ({ page }) => {
const res = await page.goto('http://localhost:3000/admin');
console.log('status:', res?.status());
expect(res?.status()).toBe(401);
await expect(page.getByRole('heading')).toHaveText('401 Unauthorized');
});
$ npx playwright test --project=no-auth tests/no-auth/page.spec.ts
Running 1 test using 1 worker
status: 401
✓ 1 [no-auth] › tests/no-auth/page.spec.ts:3:1 › 認証情報なしでは 401 になる (110ms)
1 passed (729ms)
----- server.log -----
port=3000 GET / auth=- -> 401
port=3000 GET /admin auth=- -> 401
page.goto() did not throw an error and returned the 401 response as is. The test finished in 110ms without stopping. The first line of server.log, GET /, is a request that came from the url in the webServer setting in the config file, not from the test (it appears in every later log too). The official webServer documentation says the server is considered ready when url returns a 2xx, 3xx, or 400–403 status. So startup could be detected even with this server, which returns 401.
Opening the page with httpCredentials in the config file
Write the username and password in the test option httpCredentials. To keep the password out of the repository, I read it from environment variables. I split the projects so that only tests needing credentials are in tests/auth.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: 'list',
workers: 1,
webServer: { command: 'node server.mjs', url: 'http://localhost:3000' },
use: { browserName: 'chromium' },
projects: [
{ name: 'no-auth', testDir: './tests/no-auth' },
{
name: 'auth',
testDir: './tests/auth',
use: {
httpCredentials: {
username: process.env.BASIC_USER ?? '',
password: process.env.BASIC_PASS ?? '',
},
},
},
{ name: 'api', testDir: './tests/api' },
],
});
The test code contains no authentication logic. After opening /admin, it uses page.goto() to also move to /admin/users on the same origin.
// tests/auth/config.spec.ts
import { test, expect } from '@playwright/test';
test('設定ファイルの httpCredentials でページを開ける', async ({ page }) => {
const res = await page.goto('http://localhost:3000/admin');
console.log('status:', res?.status());
expect(res?.status()).toBe(200);
await expect(page.getByRole('heading', { name: '管理画面' })).toBeVisible();
await expect(page.getByText('ログイン中: tester')).toBeVisible();
// A link on the same page can also be opened while still authenticated
const res2 = await page.goto('http://localhost:3000/admin/users');
console.log('status (2ページ目):', res2?.status());
expect(res2?.status()).toBe(200);
});
$ env BASIC_USER=tester BASIC_PASS=s3cret npx playwright test tests/auth/config.spec.ts
Running 1 test using 1 worker
status: 200
status (2ページ目): 200
✓ 1 [auth] › tests/auth/config.spec.ts:3:1 › 設定ファイルの httpCredentials でページを開ける (119ms)
1 passed (736ms)
----- server.log -----
port=3000 GET / auth=- -> 401
port=3000 GET /admin auth=- -> 401
port=3000 GET /admin auth=tester -> 200
port=3000 GET /admin/users auth=tester -> 200
The status code returned by page.goto() was 200. However, server.log shows that the server received two requests for /admin. The first was sent without an Authorization header and got a 401. The second resent it with the username and password. As the official httpCredentials documentation describes, when no origin is specified, the credentials are sent after a response that requires authentication (401). The second page, /admin/users, already had the Authorization header from the start.

When I ran the same test with the environment variables set to empty values, the retry with an empty username got 401, and the test failed. It appeared as a failure with Expected: 200 and Received: 401.
$ env BASIC_USER= BASIC_PASS= npx playwright test tests/auth/config.spec.ts
Running 1 test using 1 worker
status: 401
✘ 1 [auth] › tests/auth/config.spec.ts:3:1 › 設定ファイルの httpCredentials でページを開ける (117ms)
Error: expect(received).toBe(expected) // Object.is equality
Expected: 200
Received: 401
(エラーの詳しい表示は省略)
1 failed
----- server.log -----
port=3000 GET / auth=- -> 401
port=3000 GET /admin auth=- -> 401
port=3000 GET /admin auth= -> 401
When I used a wrong password (test.use({ httpCredentials: { username: 'tester', password: 'wrong' } })), page.goto() also returned 401. The credentials were resent only once, and then it stopped.
Specifying origin to limit which server receives the credentials
Without an origin, the credentials are sent to any server that returns 401, including servers that are not under test. If you write origin in the form scheme://host:port, the credentials go only to that origin.
// tests/auth/origin.spec.ts
import { test, expect } from '@playwright/test';
test.use({
httpCredentials: { username: 'tester', password: 's3cret', origin: 'http://localhost:3000' },
});
test('origin を指定すると、ほかのオリジンには送らない', async ({ page }) => {
const a = await page.goto('http://localhost:3000/admin');
console.log('3000:', a?.status());
const b = await page.goto('http://localhost:3001/admin');
console.log('3001:', b?.status());
expect(a?.status()).toBe(200);
expect(b?.status()).toBe(401);
});
$ npx playwright test tests/auth/origin.spec.ts
Running 1 test using 1 worker
3000: 200
3001: 401
✓ 1 [auth] › tests/auth/origin.spec.ts:7:1 › origin を指定すると、ほかのオリジンには送らない (85ms)
1 passed (770ms)
----- server.log -----
port=3000 GET / auth=- -> 401
port=3000 GET /admin auth=- -> 401
port=3000 GET /admin auth=tester -> 200
port=3001 GET /admin auth=- -> 401
The server on port 3001 also returned 401, but it was not resent with an Authorization header; there was only the single request with auth=-. You can make sure the password is sent only to the server under test.
When using different users per origin, wrap the array one more level
httpCredentials also accepts an array. According to the official documentation, the first element that matches the request's origin is used. However, when passing an array to test.use(), as the official documentation describes, you wrap it in one more array and add { scope: 'test' } as the second item.
// tests/auth/array.spec.ts
test.use({
httpCredentials: [[
{ username: 'tester', password: 's3cret', origin: 'http://localhost:3000' },
{ username: 'viewer', password: 'v1ewer', origin: 'http://localhost:3001' },
], { scope: 'test' }],
});
With this form, tester was sent to port 3000 and viewer to port 3001, and both returned 200.
$ npx playwright test tests/auth/array.spec.ts
(テストの結果の表示は省略)
----- server.log -----
port=3000 GET / auth=- -> 401
port=3000 GET /admin auth=- -> 401
port=3000 GET /admin auth=tester -> 200
port=3001 GET /admin auth=- -> 401
port=3001 GET /admin auth=viewer -> 200
I also tried two other ways of wrapping.
| Form | Result |
|---|---|
[[array], { scope: 'test' }] |
Both port 3000 and port 3001 return 200 |
Passing the array as is ([{ tester }, { viewer }]) |
Runs without error. Port 3000 returns 200, port 3001 returns 401, and viewer is not sent |
[[array]] (without { scope: 'test' }) |
Fails with browser.newContext: httpCredentials[0].username: expected string, got undefined |
When the array was passed as is, only the first element was used; the second was ignored. Since this does not produce a configuration error, you only notice the 401 when you open a page on the second origin.
Setting credentials partway through a test
When you want to compare how a page looks before and after logging in, you can set credentials partway through a test with browserContext.setHTTPCredentials(). I opened the page with no credentials first, then set them and reopened it, and finally passed null and opened it once more.
// tests/no-auth/set-credentials.spec.ts
import { test, expect } from '@playwright/test';
test('テストの途中で setHTTPCredentials を使う', async ({ page, context }) => {
const a = await page.goto('http://localhost:3000/admin');
console.log('設定前:', a?.status());
await context.setHTTPCredentials({ username: 'tester', password: 's3cret' });
const b = await page.goto('http://localhost:3000/admin');
console.log('設定後:', b?.status());
await context.setHTTPCredentials(null);
const c = await page.goto('http://localhost:3000/admin');
console.log('null にした後:', c?.status());
expect(a?.status()).toBe(401);
expect(b?.status()).toBe(200);
});
$ npx playwright test tests/no-auth/set-credentials.spec.ts
Running 1 test using 1 worker
設定前: 401
設定後: 200
null にした後: 200
✓ 1 [no-auth] › tests/no-auth/set-credentials.spec.ts:3:1 › テストの途中で setHTTPCredentials を使う (118ms)
1 passed (772ms)
----- server.log -----
port=3000 GET / auth=- -> 401
port=3000 GET /admin auth=- -> 401
port=3000 GET /admin auth=- -> 401
port=3000 GET /admin auth=tester -> 200
port=3000 GET /admin auth=tester -> 200
Even after setting null, the browser kept sending the tester credentials and got 200. The official reference notes that the browser may remember credentials for each origin it has authenticated against, so changing them may have no effect for an origin that has already been authenticated.
To confirm that "without credentials you get 401," don't rely on clearing with setHTTPCredentials(null). Instead, check it in a test that has no credentials configured (the no-auth project in this article). As the official documentation explains, each test gets a new browser context, so credentials set in a previous test are not carried over.
For API tests, send: 'always' sends credentials from the first request
httpCredentials also works for tests that call APIs through request. This has a send option: 'unauthorized' (the default) sends credentials only after receiving a 401, while 'always' adds the Authorization header from the first request. According to the official documentation, send applies only to requests sent through request (APIRequestContext), not to requests made by the browser.
// tests/api/request.spec.ts
import { test, expect } from '@playwright/test';
for (const send of ['unauthorized', 'always'] as const) {
test(`request で send: '${send}'`, async ({ playwright }) => {
const api = await playwright.request.newContext({
httpCredentials: { username: 'tester', password: 's3cret', send },
});
const res = await api.get(`http://localhost:3000/api/${send}`);
console.log(send, 'status:', res.status());
expect(res.status()).toBe(200);
await api.dispose();
});
}
$ npx playwright test tests/api
Running 2 tests using 1 worker
unauthorized status: 200
✓ 1 [api] › tests/api/request.spec.ts:4:3 › request で send: 'unauthorized' (32ms)
always status: 200
✓ 2 [api] › tests/api/request.spec.ts:4:3 › request で send: 'always' (12ms)
2 passed (623ms)
----- server.log -----
port=3000 GET / auth=- -> 401
port=3000 GET /api/unauthorized auth=- -> 401
port=3000 GET /api/unauthorized auth=tester -> 200
port=3000 GET /api/always auth=tester -> 200
Both results were 200, but the number of requests that reached the server differed: two for 'unauthorized' and one for 'always'. According to the official documentation, 'unauthorized' sends credentials only after receiving a 401 with a WWW-Authenticate header. For APIs that do not return such a 401, use 'always'.





