How to Set Cookies and localStorage Before Running Playwright Tests
When you want a Playwright test to start with the cookie consent banner already closed, or with dark mode already selected, set the values before the page opens. Cookies can be set with context.addCookies(), and localStorage can be set with page.addInitScript(). If you want to set both together, you can also write an object for storageState in test.use().
I tried all three methods in my test environment and confirmed that in each case the values take effect from the first screen shown when the page opens. I also report the results as they were for three other cases: writing localStorage with page.evaluate() after the page is open does not change the screen, addInitScript rewrites the value every time the page is opened again, and a wrong origin means localStorage is not set.
The test environment was Ubuntu 24.04.5, Node.js 22.23.5, @playwright/test 1.63.0 (Chromium 158.0.8127.36, headless), and TypeScript 5.9.3. The page under test was a server I wrote for this check, running locally. I did not test Firefox or WebKit, sessionStorage or IndexedDB, saving login state to a file and reusing it (covered in the separate article "How to save login state in Playwright and reuse it in tests"), or cookies on domains other than localhost and on subdomains.
The page used for testing
A server written only with the Node.js http module (server.mjs) returns a page with the following behavior.
- Only when the request has no cookie
consent=yes, the server puts a cookie consent banner into the HTML. - When the page opens, its script reads
themefrom localStorage and shows it on screen as "Theme: dark" (light if no value is set). - The "Switch theme" button switches between dark and light and writes the value to localStorage.
The server logs the cookies of each request it receives. Playwright starts it through webServer in the config, and stdout: 'pipe' sends the server log into the test output. The file name comments at the top of each code block (// playwright.config.ts and // tests/…) were added for this article and are not in the actual files. The output shown is only the part needed to explain each point.
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
reporter: 'list',
workers: 1,
use: { ...devices['Desktop Chrome'], baseURL: 'http://localhost:3200' },
webServer: {
command: 'node server.mjs',
url: 'http://localhost:3200',
reuseExistingServer: false,
stdout: 'pipe',
},
});
When the page was opened with nothing set, the banner appeared and the theme was light.
test('何も入れないと、バナーが出てテーマは light', async ({ page }) => {
await page.goto('/');
await expect(page.getByRole('dialog', { name: 'Cookie の同意' })).toBeVisible();
await expect(page.locator('#theme')).toHaveText('テーマ: light');
});
Set cookies with addCookies
Call addCookies() on the context (browser context) that the test receives as an argument, passing the cookie name, value, and URL. The key point is to call it before goto opens the page.
// tests/add-cookies.spec.ts
import { test, expect } from '@playwright/test';
test('addCookies で consent を入れてから開く', async ({ page, context }) => {
await context.addCookies([
{ name: 'consent', value: 'yes', url: 'http://localhost:3200' },
]);
await page.goto('/');
await expect(page.getByRole('dialog', { name: 'Cookie の同意' })).toHaveCount(0);
console.log(await context.cookies());
});
The test passed and the banner did not appear. The server log shows that consent=yes arrived with the first request. (The lines before Running come from webServer checking that the server had started.) When I read the cookie back with context.cookies(), domain: 'localhost' and path: '/' had been filled in from url. The second test in this file is the example without url, explained next.
[WebServer] [server] http://localhost:3200
[WebServer] [server] GET / cookie=""
Running 2 tests using 1 worker
[WebServer] [server] GET / cookie="consent=yes"
[
{
name: 'consent',
value: 'yes',
domain: 'localhost',
path: '/',
expires: -1,
httpOnly: false,
secure: false,
sameSite: 'Lax'
}
]
✓ 1 tests/add-cookies.spec.ts:3:5 › addCookies で consent を入れてから開く (132ms)
When I passed only the name and value without url, the test stopped with the following error. The official documentation also says that either url, or the combination of domain and path, is required.
Error: browserContext.addCookies: Cookie should have a url or a domain/path pair
localStorage: writing after the page opens is too late
First I tried writing with page.evaluate(), which runs JavaScript inside the page. Because it runs inside the page, the write happens after the page has already been opened.
// tests/evaluate.spec.ts
test('開いたあとに localStorage を書いても、画面はすぐには変わらない', async ({ page }) => {
await page.goto('/');
await page.evaluate(() => localStorage.setItem('theme', 'dark'));
await expect(page.locator('#theme')).toHaveText('テーマ: light');
await page.reload();
await expect(page.locator('#theme')).toHaveText('テーマ: dark');
});
The test passed. In other words, right after the write the screen still showed light, and only after reload() reopened the page did it show dark. This is because the test page reads localStorage once, when it opens, and by the time goto finishes that read is already done.

addInitScript: write before the page's own script runs
The function passed to page.addInitScript() runs right after the page document is created and before the page's own scripts run. If you write to localStorage here, the page's script reads that value from the start.
// tests/init-script.spec.ts
test('addInitScript で、ページのスクリプトより先に書く', async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem('theme', 'dark');
});
await page.goto('/');
await expect(page.locator('#theme')).toHaveText('テーマ: dark');
});
The test passed, and the first screen shown was "Theme: dark".
It rewrites the value every time the page opens again
addInitScript does not run only once. The official documentation says it runs every time the page navigates. In my check, I opened the page in dark, switched to light with the button, and then called reload().
test('addInitScript は、開き直すたびに書き直す', async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem('theme', 'dark');
});
await page.goto('/');
await page.getByRole('button', { name: 'テーマを切り替える' }).click();
await expect(page.locator('#theme')).toHaveText('テーマ: light');
await page.reload();
console.log('開き直したあと:', await page.locator('#theme').textContent());
});
開き直したあと: テーマ: dark
✓ 2 tests/init-script.spec.ts:11:5 › addInitScript は、開き直すたびに書き直す (170ms)
I switched to light with the button, but after reopening the page it went back to dark. This is because addInitScript wrote dark again before the page's script ran on reopen. A test like "does the chosen theme survive a reload?" cannot be checked this way.
If you write only when no value exists yet, the page starts in dark at first, and the switched value remains after reopening.
test('まだ値がないときだけ書く', async ({ page }) => {
await page.addInitScript(() => {
if (localStorage.getItem('theme') === null) {
localStorage.setItem('theme', 'dark');
}
});
await page.goto('/');
await expect(page.locator('#theme')).toHaveText('テーマ: dark');
await page.getByRole('button', { name: 'テーマを切り替える' }).click();
await page.reload();
await expect(page.locator('#theme')).toHaveText('テーマ: light');
});
To set both together, write an object for storageState
storageState is an option for loading login state saved in a file, but it also accepts an object in place of a file path. Cookies go in cookies, and localStorage goes in origins, one entry per origin. Each item in cookies needs domain and path (see the browser.newContext() documentation).
// tests/storage-state-object.spec.ts
import { test, expect } from '@playwright/test';
// Specify cookies and localStorage together without creating a file
test.use({
storageState: {
cookies: [
{
name: 'consent', value: 'yes', domain: 'localhost', path: '/',
expires: -1, httpOnly: false, secure: false, sameSite: 'Lax',
},
],
origins: [
{
origin: 'http://localhost:3200',
localStorage: [{ name: 'theme', value: 'dark' }],
},
],
},
});
test('storageState に書いた Cookie と localStorage で始まる', async ({ page }) => {
await page.goto('/');
await expect(page.getByRole('dialog', { name: 'Cookie の同意' })).toHaveCount(0);
await expect(page.locator('#theme')).toHaveText('テーマ: dark');
});
The test passed. consent=yes arrived with the first request, the banner did not appear, and the theme started as dark.
[WebServer] [server] GET / cookie="consent=yes"
✓ 1 tests/storage-state-object.spec.ts:21:5 › storageState に書いた Cookie と localStorage で始まる (184ms)
If you write test.use() at the top of a file, it applies to all tests in that file. If you write it inside test.describe(), it applies only to that group.
A wrong origin means the values are not set
An origin is the combination of scheme, host, and port, and two URLs are the same origin only when all three match (see MDN's explanation of origin). Because the host is written differently, localhost and 127.0.0.1 are treated as different origins. I wrote origin as http://127.0.0.1:3200 and opened the page with the config's baseURL (http://localhost:3200). No error appeared, and the page started with localStorage empty. (I shortened the separator lines and omitted the Call log and what follows.)
localStorage の theme: null
✘ 1 tests/origin-mismatch.spec.ts:16:5 › origin が違うと localStorage は入らない (5.2s)
1) tests/origin-mismatch.spec.ts:16:5 › origin が違うと localStorage は入らない ───
Error: expect(locator).toHaveText(expected) failed
Locator: locator('#theme')
Expected: "テーマ: dark"
Received: "テーマ: light"
Timeout: 5000ms
If storageState seems to have no effect, check the contents with page.evaluate(() => localStorage.getItem('theme')), and check whether origin and baseURL are written the same way; that will show you the cause.
Which one to use
Based on the results, the methods can be chosen as follows.
| What to set | Method | When it takes effect |
|---|---|---|
| Cookies only | context.addCookies() |
From the first request after the call |
| localStorage only | page.addInitScript() |
Every time the page opens, before the page's scripts |
| Both, same values for the whole file | test.use({ storageState: { … } }) |
When the browser context is created |
Writing with page.evaluate() can only happen after the page is open, so for a page that reads the value on open, you need reload().





