Cookies
suggest changeA cookie is a small name/value pair. The server sends it to the client in a Set-Cookie response header, and the client sends it back on later requests in a Cookie header. Cookies are how web servers remember things between otherwise stateless HTTP requests: session ids, login tokens, language preferences, consent flags.
Dart has cookie support built into dart:io through the Cookie class. The same class is used on both sides:
- Server:
HttpRequest.cookiesholds the cookies the client sent, and you add cookies toHttpResponse.cookiesto send them. - Client: you add cookies to
HttpClientRequest.cookiesto send them, andHttpClientResponse.cookiesholds the cookies the server set.
dart:io is not available on the web. In a Flutter web app or browser code the browser manages cookies itself. This article is about server-side Dart and command-line clients.
Creating a cookie
Cookie(name, value) creates a cookie. Its attributes are mutable fields, so the cascade operator (..) is a convenient way to set them. toString() returns the cookie formatted as a Set-Cookie header value:
import 'dart:io';
void main() {
final plain = Cookie('theme', 'dark');
print(plain);
final session = Cookie('session', 'abc123')
..path = '/'
..maxAge = 3600 // seconds
..secure = true
..httpOnly = true
..sameSite = SameSite.lax;
print(session);
final expiring = Cookie('promo', 'fall2026')
..expires = DateTime.utc(2026, 11, 16, 12)
..domain = 'example.com'
..httpOnly = false;
print(expiring);
}
Output:
theme=dark; HttpOnly
session=abc123; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax
promo=fall2026; Expires=Mon, 16 Nov 2026 12:00:00 GMT; Domain=example.com
Note that a cookie made with the Cookie() constructor has httpOnly set to true by default. That is a safe default. If client-side JavaScript has to read the cookie, set httpOnly = false yourself.
Cookie attributes
| Field | Header attribute | Meaning |
|---|---|---|
expires |
Expires=<date> |
Absolute expiry time. The DateTime is formatted as an HTTP date in GMT. |
maxAge |
Max-Age=<seconds> |
Lifetime in seconds from now. If both are set, browsers use Max-Age. 0 deletes the cookie. |
domain |
Domain=<host> |
Send the cookie to this host and its subdomains. If not set, the cookie goes only to the exact host that set it. |
path |
Path=<path> |
Send the cookie only for URLs under this path. Use / for the whole site. |
secure |
Secure |
Send the cookie only over HTTPS. |
httpOnly |
HttpOnly |
Hide the cookie from JavaScript (document.cookie). |
sameSite |
SameSite=Lax/Strict/None |
Controls whether the cookie is sent on cross-site requests. |
A cookie with neither expires nor maxAge is a session cookie: the browser deletes it when it closes.
SameSite has three values:
SameSite.strict: the cookie is never sent on cross-site requests, not even when the user follows a link to your site.SameSite.lax: the cookie is sent when the user navigates to your site (top-levelGET), but not on cross-sitePOSTs, iframes orfetchcalls. Browsers use this when noSameSiteis given.SameSite.none: the cookie is sent on all requests. Browsers requireSecurewith it.
Cookie name and value rules
Cookie names must be tokens: letters, digits and characters like -, _, .. No spaces, =, ;, , or quotes. Values cannot contain spaces, commas, semicolons, backslashes or double quotes. The Cookie constructor validates both and throws a FormatException if they break the rules:
import 'dart:io';
void tryCookie(String name, String value) {
try {
final c = Cookie(name, value);
print('ok: $c');
} on FormatException {
print('error: name=${name} value=${value}');
}
}
void main() {
tryCookie('user_id', '42');
tryCookie('my cookie', 'x');
tryCookie('greeting', 'Hello, World!');
tryCookie('prefs', '{"lang":"pl"}');
}
Output:
ok: user_id=42; HttpOnly
error: name=my cookie value=x
error: name=greeting value=Hello, World!
error: name=prefs value={"lang":"pl"}
To store arbitrary text in a cookie, encode it first. Uri.encodeComponent() works for short strings. For structured data, encode it as JSON and then as Base64URL. Base64URL only uses letters, digits, -, _ and =, all of which are allowed in cookie values:
import 'dart:convert';
import 'dart:io';
void main() {
// Percent-encoding.
final greeting = Cookie('greeting', Uri.encodeComponent('Hello, World!'));
print(greeting.value);
print(Uri.decodeComponent(greeting.value));
// JSON + Base64URL.
final prefs = {'lang': 'pl', 'n': 3};
final cookie = Cookie('prefs', base64Url.encode(utf8.encode(jsonEncode(prefs))));
print(cookie.value);
final decoded = jsonDecode(utf8.decode(base64Url.decode(cookie.value)));
print(decoded['lang']);
}
Output:
Hello%2C%20World!
Hello, World!
eyJsYW5nIjoicGwiLCJuIjozfQ==
pl
See Base64 and hex encoding for more on base64Url.
Keep cookies small. Browsers limit a cookie to about 4 KB, and every cookie is sent on every matching request. Store large data on the server and put only an id in the cookie.
Parsing a Set-Cookie header
Cookie.fromSetCookieValue() parses the value of a Set-Cookie header. This is useful in clients and in tests:
import 'dart:io';
void main() {
final c = Cookie.fromSetCookieValue(
'id=a3fWa; Expires=Wed, 21 Oct 2026 07:28:00 GMT; '
'Secure; HttpOnly; SameSite=Strict; Path=/docs',
);
print('name: ${c.name}');
print('value: ${c.value}');
print('expires: ${c.expires}');
print('path: ${c.path}');
print('secure: ${c.secure}');
print('httpOnly: ${c.httpOnly}');
print('sameSite: ${c.sameSite?.name}');
}
Output:
name: id
value: a3fWa
expires: 2026-10-21 07:28:00.000Z
path: /docs
secure: true
httpOnly: true
sameSite: Strict
Unlike the constructor, a parsed cookie has httpOnly set only if the header contains HttpOnly.
Server and client with dart:io
This complete program starts an HttpServer and talks to it with HttpClient. The /login route sets two cookies, and the /me route reads them back:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((HttpRequest request) {
final response = request.response;
switch (request.uri.path) {
case '/login':
response.cookies.add(Cookie('session', 'abc123')
..path = '/'
..httpOnly = true
..sameSite = SameSite.lax);
response.cookies.add(Cookie('theme', 'dark')
..path = '/'
..maxAge = 3600
..httpOnly = false);
response.write('logged in');
case '/me':
// request.cookies is parsed from the Cookie header.
final cookies = {for (final c in request.cookies) c.name: c.value};
response.write('session=${cookies['session']} theme=${cookies['theme']}');
default:
response.statusCode = HttpStatus.notFound;
}
response.close();
});
final client = HttpClient();
final base = Uri.parse('http://127.0.0.1:${server.port}');
// 1. Log in and receive cookies.
var request = await client.getUrl(base.resolve('/login'));
var response = await request.close();
print('Set-Cookie headers:');
for (final header in response.headers['set-cookie'] ?? <String>[]) {
print(' $header');
}
final received = response.cookies;
for (final c in received) {
print('parsed: ${c.name}=${c.value} httpOnly=${c.httpOnly}');
}
await response.drain<void>();
// 2. Send the cookies back.
request = await client.getUrl(base.resolve('/me'));
request.cookies.addAll(received);
response = await request.close();
print(await response.transform(utf8.decoder).join());
client.close();
await server.close();
}
Output:
Set-Cookie headers:
session=abc123; Path=/; HttpOnly; SameSite=Lax
theme=dark; Max-Age=3600; Path=/
parsed: session=abc123 httpOnly=true
parsed: theme=dark httpOnly=false
session=abc123 theme=dark
Each cookie in HttpResponse.cookies becomes its own Set-Cookie header. When a client sends cookies, only the name=value pairs are written to the Cookie header (Cookie: session=abc123; theme=dark). The attributes only matter when the server sets the cookie.
Deleting a cookie
There is no "delete" header. To remove a cookie, set it again with the same name, path and domain, an empty value, and an expiry in the past:
import 'dart:io';
Cookie expiredCookie(String name, {String path = '/', String? domain}) {
return Cookie(name, '')
..path = path
..domain = domain
..maxAge = 0
..expires = DateTime.utc(1970);
}
void main() {
print(expiredCookie('session'));
}
Output:
session=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/; HttpOnly
The path and domain must match the original cookie. Otherwise the browser treats it as a different cookie and the old one stays.
A simple cookie jar for HttpClient
HttpClient does not remember cookies between requests. The same is true for package:http. If a command-line client has to log in and then call other endpoints, it has to store the cookies itself. Here is a minimal cookie jar that keeps cookies by name and drops expired ones:
import 'dart:io';
class CookieJar {
final Map<String, (Cookie, DateTime?)> _cookies = {};
/// Store cookies from a response.
void saveFrom(HttpClientResponse response) {
final now = DateTime.now();
for (final c in response.cookies) {
DateTime? expiresAt = c.expires;
if (c.maxAge != null) {
expiresAt = now.add(Duration(seconds: c.maxAge!));
}
if (c.value.isEmpty || (expiresAt != null && !expiresAt.isAfter(now))) {
_cookies.remove(c.name); // server deleted it
} else {
_cookies[c.name] = (c, expiresAt);
}
}
}
/// Add stored, non-expired cookies to a request.
void addTo(HttpClientRequest request) {
final now = DateTime.now();
_cookies.removeWhere((_, entry) {
final expiresAt = entry.$2;
return expiresAt != null && !expiresAt.isAfter(now);
});
for (final (cookie, _) in _cookies.values) {
request.cookies.add(Cookie(cookie.name, cookie.value));
}
}
List<String> get names => _cookies.keys.toList();
}
Using it:
// Needs: import 'dart:convert';
Future<String> get(HttpClient client, CookieJar jar, Uri url) async {
final request = await client.getUrl(url);
jar.addTo(request);
final response = await request.close();
jar.saveFrom(response);
return response.transform(utf8.decoder).join();
}
This jar ignores domain and path matching, which is fine for a client that talks to a single server. For a general-purpose client, use a package that implements the full rules, such as cookie_jar, which is commonly used together with dio through dio_cookie_manager.
Cookies in Shelf
Shelf has no cookie API of its own. You read the raw cookie header from the Request and write set-cookie headers on the Response. The Cookie class from dart:io is still useful for formatting:
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';
/// Parses "a=1; b=2" into {'a': '1', 'b': '2'}.
Map<String, String> parseCookies(Request request) {
final header = request.headers['cookie'];
if (header == null) return {};
final result = <String, String>{};
for (final pair in header.split(';')) {
final i = pair.indexOf('=');
if (i <= 0) continue;
result[pair.substring(0, i).trim()] = pair.substring(i + 1).trim();
}
return result;
}
void main() async {
final app = Router()
..get('/visit', (Request request) {
final cookies = parseCookies(request);
final visits = (int.tryParse(cookies['visits'] ?? '') ?? 0) + 1;
final visitsCookie = Cookie('visits', '$visits')
..path = '/'
..maxAge = 60 * 60 * 24 * 365
..sameSite = SameSite.lax;
final langCookie = Cookie('lang', cookies['lang'] ?? 'en')
..path = '/'
..httpOnly = false;
return Response.ok(
'You have visited $visits time(s)\n',
// A List value sends multiple Set-Cookie headers.
headers: {
'set-cookie': [visitsCookie.toString(), langCookie.toString()],
},
);
});
final server = await shelf_io.serve(app.call, 'localhost', 8080);
print('Listening on http://localhost:${server.port}');
}
Testing it with curl, saving cookies to a file between calls:
$ curl -c jar.txt -b jar.txt localhost:8080/visit
You have visited 1 time(s)
$ curl -c jar.txt -b jar.txt localhost:8080/visit
You have visited 2 time(s)
Don't join several cookies into one Set-Cookie header with commas. Commas also appear inside Expires dates, so clients can't split such a header reliably. Always send one header per cookie, as above.
For storing server-side state behind a cookie, see Sessions.
Signed cookies
The client can change any cookie. If you store something like a user id directly in a cookie, the user can edit it to become someone else. A signed cookie appends an HMAC of the value, computed with a secret key known only to the server. The server recomputes the signature on every request and rejects the cookie if it doesn't match.
This uses package:crypto (dart pub add crypto):
import 'dart:convert';
import 'package:crypto/crypto.dart';
class CookieSigner {
final Hmac _hmac;
CookieSigner(String secret) : _hmac = Hmac(sha256, utf8.encode(secret));
String _signature(String value) =>
base64Url.encode(_hmac.convert(utf8.encode(value)).bytes);
/// Returns "value.signature".
String sign(String value) => '$value.${_signature(value)}';
/// Returns the original value, or null if the signature is wrong.
String? verify(String signed) {
final i = signed.lastIndexOf('.');
if (i < 0) return null;
final value = signed.substring(0, i);
final expected = _signature(value);
final actual = signed.substring(i + 1);
return _constantTimeEquals(expected, actual) ? value : null;
}
static bool _constantTimeEquals(String a, String b) {
if (a.length != b.length) return false;
var diff = 0;
for (var i = 0; i < a.length; i++) {
diff |= a.codeUnitAt(i) ^ b.codeUnitAt(i);
}
return diff == 0;
}
}
void main() {
final signer = CookieSigner('super-secret-key');
final signed = signer.sign('alice');
print(signed);
print(signer.verify(signed));
// An attacker changes the user name but can't compute a new signature.
final tampered = signed.replaceFirst('alice', 'admin');
print(signer.verify(tampered));
}
Output:
alice.EAkNfzmnXZj4QIBtbinJ7P34gCGl4r8gCCGHDO0t9n0=
alice
null
The comparison runs in constant time so an attacker can't learn the correct signature by measuring response times. Signing only protects against tampering. The value is still readable by the client, so don't put secrets in it. Load the key from configuration and keep it out of source control.
To also give a signed cookie an expiry time that the client can't extend, include a timestamp in the signed value (for example alice|1792224000) and check it after verifying. At that point, consider a JWT or a server-side session instead.
Security checklist
- Session and auth cookies: always
httpOnly = true,secure = trueandsameSite = SameSite.lax(orstrict).HttpOnlylimits the damage of an XSS bug, andSameSiteblocks most CSRF attacks. - Use the
__Host-prefix for the most sensitive cookies, for exampleCookie('__Host-session', id). Browsers only accept such a cookie if it hasSecure,Path=/and noDomain, so a subdomain can't overwrite it. - Don't set
domainunless you need it. Without it, the cookie is sent only to the exact host that set it. - Never trust cookie contents. Validate them like any other user input, and sign them if they must not be modified.
- Generate session ids with
Random.secure(). See Random numbers. - Rotate the session id after login, so a session id planted before login (session fixation) is useless.
SameSite.nonerequiressecure = true. Browsers reject it otherwise.
Summary
| Task | Code |
|---|---|
| Create a cookie | Cookie('name', 'value')..path = '/'..maxAge = 3600 |
| Format as header value | cookie.toString() |
| Parse a Set-Cookie header | Cookie.fromSetCookieValue(header) |
| Read cookies (dart:io server) | request.cookies |
| Set cookies (dart:io server) | request.response.cookies.add(cookie) |
| Send cookies (HttpClient) | request.cookies.add(cookie) |
| Read cookies (HttpClient) | response.cookies |
| Delete a cookie | same name/path, empty value, maxAge = 0 |
| Shelf | parse request.headers['cookie'], return 'set-cookie': [...] |