grafana/k6 · error
cannot set cookies
Error message
cannot set cookies: %w
What it means
All cookies passed k6's client-side checks, but the CDP command Storage.setCookies (scoped to the browser context) rejected the batch. The wrapped error is Chromium's and typically names the first offending cookie, e.g. 'Failed to parse or set cookie named ...'. Causes are attributes CDP validates more strictly than k6's pre-checks.
Solutions
- Read the wrapped CDP message — it names the failing cookie and reason; fix that attribute
- Drop secure: true when targeting http:// origins, or serve the test over https
- Use sameSite values 'Strict', 'Lax', or 'None' (None requires secure: true)
- Express expires in seconds since epoch (Math.floor(Date.now()/1000)), not milliseconds
- Remove ';', ',', and control characters from names and values
Example fix
// before
ctx.addCookies([{
name: 'session', value: 'abc',
domain: 'localhost', path: '/',
secure: true, // rejected: origin is http://localhost
expires: Date.now(), // milliseconds, parsed as far-future
}]);
// after
ctx.addCookies([{
name: 'session', value: 'abc',
domain: 'localhost', path: '/',
secure: false,
expires: Math.floor(Date.now() / 1000) + 3600,
}]); Defensive patterns
Strategy: validation
Validate before calling
function normalizeCookie(c) {
return {
...c,
expires: c.expires ? Math.floor(c.expires / 1000) : undefined, // ms -> s if needed
secure: c.secure !== undefined ? c.secure : false, // don't mark secure for http origins
sameSite: ['Strict', 'Lax', 'None'].includes(c.sameSite) ? c.sameSite : undefined,
};
}
const cookies = rawCookies
.filter((c) => /^[^;,\s]+$/.test(c.name) && /^[^;,]+$/.test(c.value)) // no ; or ,
.map(normalizeCookie);
ctx.addCookies(cookies); Type guard
const isCdpSafeCookie = (c) => /^[^;,\s]+$/.test(c.name) && /^[^;,]+$/.test(c.value) && (c.sameSite === undefined || ['Strict', 'Lax', 'None'].includes(c.sameSite)) && !(c.secure === true && /^http:/.test(c.url || ''));
Try / catch
try {
ctx.addCookies(cookies);
} catch (e) {
if (String(e.message).includes('cannot set cookies')) {
// wrapped CDP message names the offending cookie; fix or drop it and retry
const bad = cookies.find((c) => e.message.includes(`named '${c.name}'`));
if (bad) {
ctx.addCookies(cookies.filter((c) => c !== bad));
} else {
throw e;
}
} else {
throw e;
}
} Prevention
- Don't set secure: true against http:// origins
- Express expires as epoch seconds (Date.now()/1000), never milliseconds
- Use only 'Strict'/'Lax'/'None' for sameSite, and 'None' only with secure
- Keep ';' and ',' out of cookie names and values
When it happens
Trigger: Secure cookies (secure: true) targeting an http:// origin; invalid sameSite values; illegal characters such as ';' or ',' in name/value; malformed domain syntax; an expires far out of range after unit mistakes (k6 treats expires as seconds since epoch — passing milliseconds yields an absurd date).
Common situations: Recording cookies from an HTTPS session and replaying against a local http:// server; hand-built sameSite strings; expires timestamps copied as JavaScript Date.now() (milliseconds) instead of epoch seconds.
Related errors
- adding init script to browser context
- can't fetch the page for unknown reason
- capturing screenshot
- clearing permissions
- cookie name must be set: %#v
AI-assisted analysis of grafana/k6@01ffac6f24 (2026-08-18).
Data as JSON: /api/errors/1f7539650d4605de.
Report an issue: GitHub.
Appendix: source
Thrown at internal/js/modules/k6/browser/common/browser_context.go:499
}
cookiesToSet = append(cookiesToSet, &network.CookieParam{
Name: c.Name,
Value: c.Value,
Domain: c.Domain,
Path: c.Path,
URL: c.URL,
Expires: ts,
HTTPOnly: c.HTTPOnly,
Secure: c.Secure,
SameSite: network.CookieSameSite(c.SameSite),
})
}
setCookies := storage.
SetCookies(cookiesToSet).
WithBrowserContextID(b.id)
if err := setCookies.Do(cdp.WithExecutor(b.ctx, b.browser.conn)); err != nil {
return fmt.Errorf("cannot set cookies: %w", err)
}
return nil
}
// ClearCookies clears cookies.
func (b *BrowserContext) ClearCookies() error {
b.logger.Debugf("BrowserContext:ClearCookies", "bctxid:%v", b.id)
clearCookies := storage.
ClearCookies().
WithBrowserContextID(b.id)
if err := clearCookies.Do(cdp.WithExecutor(b.ctx, b.browser.conn)); err != nil {
return fmt.Errorf("clearing cookies: %w", err)
}
return nil
}
View on GitHub (pinned to 01ffac6f24)