← Back to library
Playwrightauthadvancedv1.20+

Login via API and set auth state

Authenticate through the API and reuse the session across tests — no UI login needed.

1import { test, request } from '@playwright/test';
2
3test.beforeAll(async () => {
4  const apiContext = await request.newContext();
5
6  const response = await apiContext.post('/api/login', {
7    data: { email: 'user@test.com', password: 'secret' },
8  });
9
10  // Save auth state (cookies + localStorage) to file
11  await apiContext.storageState({ path: 'auth.json' });
12  await apiContext.dispose();
13});
14
15// In playwright.config.ts, set: storageState: 'auth.json'
16// All tests in this project will reuse the session
#login#session#storageState#api