Set a cookie before navigating

Seed a cookie on the context with addCookies, then load the page in the state you want.

Some pages read a cookie on first load: a feature flag, a stored consent choice, an A/B bucket. Set the cookie on the context with addCookies() before goto(), so the very first request carries it and the page renders in the state you want.

Add the cookie, then navigate

addCookies() takes an array of cookie arrays. Each cookie needs a name and value, plus either a url or a domain and path. Add the cookie first, then load the page.

php
$context = Playwright::chromium();

$context->addCookies([
    [
        'name' => 'feature_new_dashboard',
        'value' => 'on',
        'url' => 'https://app.example.test',
    ],
]);

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

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

The url form lets the browser derive the domain and path for you. It is the shortest correct shape for most cases.

Set the domain and path explicitly

When you need the cookie scoped to a specific host and path, give domain and path instead of url. Use this for a consent cookie that a banner would otherwise set.

php
$context->addCookies([
    [
        'name' => 'cookie_consent',
        'value' => 'accepted',
        'domain' => 'app.example.test',
        'path' => '/',
    ],
]);

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

The consent banner reads the cookie on load and stays hidden, so your test starts on the real content.

Order matters

addCookies() seeds the context, not a page. Call it before the navigation that should carry the cookie. A cookie added after goto() does not apply to a request the page already sent.

Expected result

The first navigation already sees the cookie. Verify the user-visible state that depends on it: a feature flag is active, a consent banner is hidden, or a role-specific page appears.

Go next

← All recipes