HTTP headers

suggest change

Every HTTP request and response carries a list of headers: name/value pairs that come before the body. They describe the body (Content-Type, Content-Length), control caching (Cache-Control, ETag), carry credentials (Authorization, Cookie), negotiate formats (Accept) and much more.

This article covers:

Packages used:

dart pub add http shelf crypto

The examples were run with Dart 3.13, http 1.6.0, shelf 1.4.3 and crypto 3.0.7. For the basics of writing a server with dart:io, see An HTTP server.

Header basics

On the wire, headers are plain text lines after the request or status line:

GET /users/7 HTTP/1.1
Host: api.example.com
Accept: application/json
X-Tag: red
X-Tag: blue

Rules worth knowing:

The constants on HttpHeaders give you the standard names in lowercase, so you don't mistype them: HttpHeaders.contentTypeHeader is 'content-type', HttpHeaders.cacheControlHeader is 'cache-control', and so on.

Reading and writing headers with dart:io

In dart:io, both HttpRequest/HttpClientResponse (incoming) and HttpResponse/HttpClientRequest (outgoing) expose an HttpHeaders object. It has:

This program starts a server on a random port and sends it a request with HttpClient:

import 'dart:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  server.listen((HttpRequest req) {
    final h = req.headers;
    // Names are case-insensitive.
    print('User-Agent: ${h.value('User-Agent')}');
    print('user-agent: ${h.value(HttpHeaders.userAgentHeader)}');
    // [] returns the values as a List<String>.
    print('x-tag list: ${h['x-tag']}');
    // Typed accessors for common headers.
    print('host: ${h.host}');
    print('contentType: ${h.contentType}');
    print('mimeType: ${h.contentType?.mimeType}');
    print('charset: ${h.contentType?.charset}');
    print('contentLength: ${h.contentLength}');
    print('all headers:');
    h.forEach((name, values) => print('  $name: $values'));

    final res = req.response;
    res.statusCode = HttpStatus.ok;
    res.headers.contentType = ContentType.json;
    res.headers.set('X-Request-Id', 'abc123');
    res.headers.add('X-Tag', 'one');
    res.headers.add('X-Tag', 'two');
    res.headers.set(HttpHeaders.cacheControlHeader, 'no-store');
    res.write('{"ok":true}');
    res.close();
  });

  final client = HttpClient();
  final request = await client.post('localhost', server.port, '/items');
  request.headers
    ..set(HttpHeaders.userAgentHeader, 'demo/1.0')
    ..add('X-Tag', 'red')
    ..add('X-Tag', 'blue')
    ..set(HttpHeaders.acceptHeader, 'application/json, text/plain;q=0.5')
    ..contentType = ContentType('application', 'json', charset: 'utf-8');
  request.write('{"name":"pen"}');
  final response = await request.close();
  print('--- client got ${response.statusCode}');
  response.headers.forEach((name, values) => print('  $name: $values'));
  print('x-tag: ${response.headers['x-tag']}');
  print('x-request-id: ${response.headers.value('x-request-id')}');
  await response.drain<void>();
  client.close();
  await server.close();
}

Output:

User-Agent: demo/1.0
user-agent: demo/1.0
x-tag list: [red, blue]
host: localhost
contentType: application/json; charset=utf-8
mimeType: application/json
charset: utf-8
contentLength: -1
all headers:
  user-agent: [demo/1.0]
  x-tag: [red, blue]
  accept: [application/json, text/plain;q=0.5]
  transfer-encoding: [chunked]
  accept-encoding: [gzip]
  host: [localhost:65177]
  content-type: [application/json; charset=utf-8]
--- client got 200
  cache-control: [no-store]
  x-tag: [one, two]
  transfer-encoding: [chunked]
  x-frame-options: [SAMEORIGIN]
  content-type: [application/json; charset=utf-8]
  x-xss-protection: [1; mode=block]
  x-content-type-options: [nosniff]
  x-request-id: [abc123]
x-tag: [one, two]
x-request-id: abc123

Things to notice:

Repeated headers and value()

value() is for headers that should appear once. If the header has several values it throws:

try {
  response.headers.value('x-tag'); // X-Tag: one / X-Tag: two
} on HttpException catch (e) {
  print(e);
}
HttpException: More than one value for header x-tag

Use headers['x-tag'] when a header can repeat.

What dart:io sends for repeated values differs from what it receives. A raw socket server shows what goes over the wire:

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  // A raw TCP server prints exactly what the client sends.
  final raw = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  raw.listen((s) async {
    final data = await s.first;
    print(utf8.decode(data).trim());
    s.write('HTTP/1.1 200 OK\r\n'
        'X-Tag: one\r\nX-Tag: two\r\n'
        'Set-Cookie: a=1\r\nSet-Cookie: b=2\r\n'
        'Content-Length: 0\r\nConnection: close\r\n\r\n');
    await s.close();
  });

  final client = HttpClient();
  final rq = await client.get('localhost', raw.port, '/');
  rq.headers.add('x-tag', 'red');
  rq.headers.add('x-tag', 'blue');
  rq.headers.set('X-Api-Key', 'k1', preserveHeaderCase: true);
  rq.headers.removeAll(HttpHeaders.acceptEncodingHeader);
  final rs = await rq.close();
  print('x-tag: ${rs.headers['x-tag']} (${rs.headers['x-tag']!.length} values)');
  print('set-cookie: ${rs.headers['set-cookie']}');
  await rs.drain<void>();
  client.close();
  await raw.close();
}

Output:

GET / HTTP/1.1
user-agent: Dart/3.13 (dart:io)
x-tag: red, blue
X-Api-Key: k1
host: localhost:56135
x-tag: [one, two] (2 values)
set-cookie: [a=1, b=2]

Headers are locked once the body starts

Headers are sent before the body, so they can't change after you start writing it:

req.response.write('hi');
try {
  req.response.headers.set('x-late', '1');
} on HttpException catch (e) {
  print(e);
}
HttpException: HTTP headers are not mutable

The headers of an incoming request are read-only too, and throw the same exception. Set the status code and all headers first, then write the body.

Invalid values are rejected

dart:io validates names and values. A value containing a line break throws a FormatException instead of being sent, which protects you from header injection (an attacker who controls a value adding their own headers):

try {
  rq.headers.set('x-bad', 'a\r\nInjected: yes');
} on FormatException catch (e) {
  print(e.message);
}
try {
  rq.headers.set('bad name', 'x');
} on FormatException catch (e) {
  print(e.message);
}
Invalid HTTP header field value: "a\r\nInjected: yes"
Invalid HTTP header field name: "bad name"

Still validate user input that ends up in headers, such as a file name in Content-Disposition or a URL in Location, so the request fails with a clear error instead of an exception deep in your handler.

Headers in package:http

package:http is the usual way to make requests (see HTTP Request and REST APIs). It uses plain Map<String, String> for headers:

import 'dart:io';

import 'package:http/http.dart' as http;

Future<void> main() async {
  final raw = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
  raw.listen((s) async {
    await s.first;
    s.write('HTTP/1.1 200 OK\r\n'
        'Content-Type: text/plain\r\n'
        'X-Tag: one\r\nX-Tag: two\r\n'
        'Set-Cookie: a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT\r\n'
        'Set-Cookie: b=2\r\n'
        'Content-Length: 2\r\nConnection: close\r\n\r\nok');
    await s.close();
  });

  final r = await http.get(
    Uri.parse('http://localhost:${raw.port}/'),
    headers: {'Accept': 'text/plain', 'X-Api-Key': 'k1'},
  );
  print(r.headers);
  print(r.headers['X-Tag']); // keys are lowercase: this is null
  print(r.headers['x-tag']);
  print(r.headersSplitValues['x-tag']);
  print(r.headersSplitValues['set-cookie']);
  await raw.close();
}

Output:

{connection: close, content-type: text/plain, set-cookie: a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT,b=2, x-tag: one,two, content-length: 2}
null
one,two
[one, two]
[a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT, b=2]

Headers in Shelf

Shelf wraps dart:io with immutable Request and Response objects. Their headers are:

When you create a Response, the headers map can have a String or a List<String> as each value:

import 'dart:convert';
import 'dart:io';

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

Response handler(Request request) {
  // Shelf header maps are case-insensitive.
  print('User-Agent: ${request.headers['User-Agent']}');
  print('x-tag (joined): ${request.headers['x-tag']}');
  print('x-tag (all): ${request.headersAll['x-tag']}');
  // Parsed from Content-Type and Content-Length.
  print('mimeType: ${request.mimeType} encoding: ${request.encoding?.name}');
  print('contentLength: ${request.contentLength}');
  return Response.ok(
    'hello',
    headers: {
      'content-type': 'text/plain; charset=utf-8',
      'cache-control': 'no-cache',
      'x-tag': ['one', 'two'],
    },
  );
}

Future<void> main() async {
  final server = await shelf_io.serve(handler, InternetAddress.loopbackIPv4, 0);
  // Send a raw request so we control exactly which headers are sent.
  final s = await Socket.connect('localhost', server.port);
  s.write('GET / HTTP/1.1\r\nHost: localhost\r\nUser-Agent: raw\r\n'
      'X-Tag: red\r\nX-Tag: blue\r\n'
      'Content-Type: text/plain; charset=utf-8\r\nContent-Length: 0\r\n'
      'Connection: close\r\n\r\n');
  print(await utf8.decoder.bind(s).join());
  await s.close();
  await server.close();
}

Output:

User-Agent: raw
x-tag (joined): red,blue
x-tag (all): [red, blue]
mimeType: text/plain encoding: utf-8
contentLength: 0
HTTP/1.1 200 OK
x-powered-by: Dart with package:shelf
connection: close
cache-control: no-cache
x-tag: one, two
date: Sat, 17 Oct 2026 20:39:06 GMT
content-length: 5
x-frame-options: SAMEORIGIN
content-type: text/plain; charset=utf-8
x-xss-protection: 1; mode=block
x-content-type-options: nosniff

hello

Shelf added x-powered-by and date, and dart:io underneath added its usual three security headers.

To add or replace headers on an existing request or response, use change. Headers you pass are merged into the existing ones, replacing headers with the same name, and a null value removes a header:

final changed = response.change(headers: {
  'x-request-id': id, // add or replace
  'x-powered-by': null, // remove
});

Use lowercase names with change. The merge copies the headers into an ordinary map first, so removing 'X-Powered-By' with a null doesn't match an existing x-powered-by header.

Because a Shelf handler is just a function, you can test header logic by building a Request yourself, without a server:

final request = Request(
  'GET',
  Uri.parse('http://localhost/users/7'),
  headers: {'accept': 'application/json'},
);
final response = await handler(request);
print(response.headers['content-type']);

The next sections use this style. For more on Shelf middleware, which is where most header handling belongs, see HTTP middleware.

Parsing structured header values

Many header values have a main value followed by ;-separated parameters. dart:io has parsers for them:

import 'dart:io';

void main() {
  final ct = ContentType.parse('text/html; charset=UTF-8');
  print('${ct.primaryType} ${ct.subType} ${ct.mimeType} ${ct.charset}');
  print(ct);

  final cd = HeaderValue.parse('attachment; filename="report 2026.pdf"');
  print('${cd.value} ${cd.parameters}');

  // Building a value: parameters are quoted when needed.
  final out = HeaderValue('form-data', {'name': 'file', 'filename': 'a b.txt'});
  print(out);

  print(ContentType.json);
  print(ContentType.html);
  print(ContentType.text);
  print(ContentType.binary);
  print(ContentType('image', 'svg+xml'));

  // Dates in headers use the RFC 1123 format, always in GMT.
  final d = DateTime.utc(2026, 10, 17, 8, 30);
  final s = HttpDate.format(d);
  print(s);
  print(HttpDate.parse(s));
  try {
    HttpDate.parse('2026-10-17');
  } on HttpException catch (e) {
    print(e);
  }
}

Output:

text html text/html utf-8
text/html; charset=utf-8
attachment {filename: report 2026.pdf}
form-data; name=file; filename="a b.txt"
application/json; charset=utf-8
text/html; charset=utf-8
text/plain; charset=utf-8
application/octet-stream
image/svg+xml
Sat, 17 Oct 2026 08:30:00 GMT
2026-10-17 08:30:00.000Z
HttpException: Invalid HTTP date 2026-10-17

HttpDate is the right tool for Date, Expires, Last-Modified, If-Modified-Since and Retry-After (when it's a date). Shelf's request.ifModifiedSince and response.lastModified/expires use it for you. For general date handling see Basic usage of DateTime.

Content negotiation with Accept

A client says which formats it prefers in Accept, with optional quality values (q, from 0 to 1, default 1):

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

The server picks the best format it can produce. The rule: the q of a format comes from the most specific range that matches it (text/html beats text/* beats */*), and q=0 means "not acceptable". Neither dart:io nor Shelf does this for you, but it's short:

import 'dart:convert';

import 'package:shelf/shelf.dart';

/// One entry of an Accept header, such as `text/html;q=0.8`.
typedef MediaRange = ({String type, double q});

List<MediaRange> parseAccept(String? header) {
  if (header == null || header.trim().isEmpty) {
    return [(type: '*/*', q: 1.0)];
  }
  final ranges = <MediaRange>[];
  for (final part in header.split(',')) {
    final [type, ...params] = part.split(';');
    if (type.trim().isEmpty) continue;
    var q = 1.0;
    for (final param in params) {
      final [name, ...value] = param.split('=');
      if (name.trim() == 'q' && value.isNotEmpty) {
        q = double.tryParse(value.first.trim()) ?? 0;
      }
    }
    ranges.add((type: type.trim().toLowerCase(), q: q));
  }
  return ranges;
}

/// How specific [range] is for [type]: -1 = no match, 0 = */*,
/// 1 = text/*, 2 = exact match.
int specificity(String range, String type) {
  if (range == type) return 2;
  if (range.endsWith('/*') &&
      type.startsWith(range.substring(0, range.length - 1))) {
    return 1;
  }
  return range == '*/*' ? 0 : -1;
}

/// Returns the best of [available] for [acceptHeader], or null.
/// The q value of a type comes from the most specific matching range.
String? negotiate(String? acceptHeader, List<String> available) {
  final ranges = parseAccept(acceptHeader);
  String? best;
  var bestQ = 0.0;
  for (final type in available) {
    var q = 0.0;
    var mostSpecific = -1;
    for (final range in ranges) {
      final s = specificity(range.type, type);
      if (s > mostSpecific) {
        mostSpecific = s;
        q = range.q;
      }
    }
    // Strictly greater: on a tie, the server's order of preference wins.
    if (q > bestQ) {
      best = type;
      bestQ = q;
    }
  }
  return best;
}

Response userHandler(Request request) {
  const user = {'id': 7, 'name': 'Alice'};
  final type = negotiate(
    request.headers['accept'],
    ['application/json', 'text/html', 'text/plain'],
  );
  // The response depends on Accept, so caches must key on it.
  const vary = {'vary': 'Accept'};
  return switch (type) {
    'application/json' => Response.ok(jsonEncode(user),
        headers: {...vary, 'content-type': 'application/json'}),
    'text/html' => Response.ok('<h1>${user['name']}</h1>',
        headers: {...vary, 'content-type': 'text/html; charset=utf-8'}),
    'text/plain' => Response.ok('User ${user['id']}: ${user['name']}',
        headers: {...vary, 'content-type': 'text/plain; charset=utf-8'}),
    _ => Response(406, body: 'Not Acceptable', headers: vary),
  };
}

Future<void> main() async {
  for (final accept in [
    null,
    'application/json',
    'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'text/*;q=0.5, application/json;q=0.4',
    'application/json;q=0, */*',
    'image/png',
  ]) {
    final request = Request('GET', Uri.parse('http://localhost/users/7'),
        headers: {if (accept != null) 'accept': accept});
    final response = userHandler(request);
    print('Accept: $accept');
    print('  ${response.statusCode} ${response.headers['content-type']} '
        '${await response.readAsString()}');
  }
}

Output:

Accept: null
  200 application/json {"id":7,"name":"Alice"}
Accept: application/json
  200 application/json {"id":7,"name":"Alice"}
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  200 text/html; charset=utf-8 <h1>Alice</h1>
Accept: text/*;q=0.5, application/json;q=0.4
  200 text/html; charset=utf-8 <h1>Alice</h1>
Accept: application/json;q=0, */*
  200 text/html; charset=utf-8 <h1>Alice</h1>
Accept: image/png
  406 null Not Acceptable

Vary: Accept tells browsers and CDNs that the same URL returns different bodies for different Accept values, so a cached HTML response isn't served to a client that asked for JSON. Add every request header the response depends on to Vary, for example Vary: Accept, Accept-Language (see Localization for Accept-Language).

Many APIs skip negotiation and always return JSON. Returning 406 for an unsupported Accept is optional too; sending your default format is also allowed.

Conditional requests: ETag and Last-Modified

Conditional requests let a client ask "has this changed since I last fetched it?". If not, the server answers 304 Not Modified with no body, which saves bandwidth.

There are two validators:

When both are present, If-None-Match takes priority. This Shelf handler supports both:

import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

var report = 'Sales: 42';
var reportModified = DateTime.utc(2026, 10, 1, 12);

String etagFor(List<int> bytes) =>
    '"${sha256.convert(bytes).toString().substring(0, 16)}"';

/// True if any tag in an If-None-Match header matches [etag].
bool etagMatches(String header, String etag) {
  if (header.trim() == '*') return true;
  // Weak comparison: W/"x" and "x" are the same for If-None-Match.
  String strip(String t) => t.trim().replaceFirst('W/', '');
  return header.split(',').map(strip).contains(strip(etag));
}

Response reportHandler(Request request) {
  final body = utf8.encode(report);
  final etag = etagFor(body);
  final headers = {
    'etag': etag,
    'last-modified': HttpDate.format(reportModified),
    'cache-control': 'no-cache', // store it, but revalidate every time
    'content-type': 'text/plain; charset=utf-8',
  };

  final ifNoneMatch = request.headers['if-none-match'];
  final ifModifiedSince = request.ifModifiedSince; // parsed by Shelf
  final notModified = ifNoneMatch != null
      ? etagMatches(ifNoneMatch, etag) // If-None-Match wins when present
      : ifModifiedSince != null &&
          !reportModified.isAfter(ifModifiedSince);
  if (notModified) {
    return Response.notModified(headers: headers);
  }
  return Response.ok(body, headers: headers);
}

Future<void> main() async {
  final server =
      await shelf_io.serve(reportHandler, InternetAddress.loopbackIPv4, 0);
  final url = Uri.parse('http://localhost:${server.port}/report');

  final first = await http.get(url);
  final etag = first.headers['etag']!;
  final lastModified = first.headers['last-modified']!;
  print('1: ${first.statusCode} etag=$etag body="${first.body}"');

  final second = await http.get(url, headers: {'if-none-match': etag});
  print('2: ${second.statusCode} body="${second.body}"');

  final third =
      await http.get(url, headers: {'if-modified-since': lastModified});
  print('3: ${third.statusCode} (If-Modified-Since: $lastModified)');

  report = 'Sales: 43';
  reportModified = DateTime.utc(2026, 10, 2, 9);
  final fourth = await http.get(url, headers: {'if-none-match': etag});
  print('4: ${fourth.statusCode} etag=${fourth.headers['etag']} '
      'body="${fourth.body}"');

  await server.close();
}

Output:

1: 200 etag="e68ac81131e53e40" body="Sales: 42"
2: 304 body=""
3: 304 (If-Modified-Since: Thu, 01 Oct 2026 12:00:00 GMT)
4: 200 etag="25b6cca1fced3533" body="Sales: 43"

Notes:

For serving whole directories with ETag/Last-Modified handled for you, use shelf_static.

Cache-Control

Cache-Control tells browsers, proxies and CDNs whether and for how long they may store a response. Common values:

Value Use for
no-store sensitive data that must never be written to a cache
no-cache may be stored, but must be revalidated (with ETag) before each use
private, max-age=60 per-user data a browser may reuse for 60 seconds, but a CDN must not store
public, max-age=300 shared data anyone may cache for 5 minutes
max-age=600, s-maxage=3600 browsers cache 10 minutes, shared caches (CDNs) 1 hour
public, max-age=31536000, immutable files with a content hash in the name, like app.3f9a1c.js

Note that no-cache doesn't mean "don't cache". Use no-store for that.

On the client side you may need to read Cache-Control, for example to decide how long to keep an API response in memory (see Caching). It's a comma-separated list of directives, some with values:

/// Parses `Cache-Control` into a map. Directives without a value map to null.
Map<String, String?> parseCacheControl(String? header) {
  final result = <String, String?>{};
  if (header == null) return result;
  for (final directive in header.split(',')) {
    final [name, ...rest] = directive.split('=');
    if (name.trim().isEmpty) continue;
    final value = rest.isEmpty ? null : rest.join('=').trim();
    result[name.trim().toLowerCase()] = value?.replaceAll('"', '');
  }
  return result;
}

/// How long a private cache (a browser or HTTP client) may reuse a response
/// without revalidating. Shared caches (CDNs) prefer s-maxage over max-age.
Duration? freshFor(Map<String, String?> cc) {
  if (cc.containsKey('no-store') || cc.containsKey('no-cache')) return null;
  final maxAge = int.tryParse(cc['max-age'] ?? '');
  return maxAge == null ? null : Duration(seconds: maxAge);
}

void main() {
  for (final header in [
    'public, max-age=31536000, immutable',
    'private, max-age=60',
    'max-age=600, s-maxage=3600',
    'no-store',
    'no-cache, private',
  ]) {
    final cc = parseCacheControl(header);
    print('$header\n  $cc fresh for: ${freshFor(cc)}');
  }
}

Output:

public, max-age=31536000, immutable
  {public: null, max-age: 31536000, immutable: null} fresh for: 8760:00:00.000000
private, max-age=60
  {private: null, max-age: 60} fresh for: 0:01:00.000000
max-age=600, s-maxage=3600
  {max-age: 600, s-maxage: 3600} fresh for: 0:10:00.000000
no-store
  {no-store: null} fresh for: null
no-cache, private
  {no-cache: null, private: null} fresh for: null

HeaderValue.parse isn't a good fit here, because Cache-Control uses commas, not semicolons, between directives.

Security headers

A few response headers make browsers stricter and close whole classes of attacks. They matter for anything a browser loads, including JSON APIs:

Header Effect
Strict-Transport-Security: max-age=63072000; includeSubDomains browser uses only HTTPS for this host for 2 years (send it only over HTTPS)
X-Content-Type-Options: nosniff browser trusts Content-Type instead of guessing
X-Frame-Options: DENY page can't be embedded in a frame (clickjacking)
Content-Security-Policy: ... which sources scripts, styles, images and frames may come from
Referrer-Policy: strict-origin-when-cross-origin limits how much of the URL leaks in Referer
Permissions-Policy: camera=(), microphone=() disables browser features the site doesn't use

As shown earlier, HttpServer already sends three headers on every response. They live in server.defaultResponseHeaders, and you can change or clear them:

x-frame-options: SAMEORIGIN
content-type: text/plain; charset=utf-8
x-xss-protection: 1; mode=block
x-content-type-options: nosniff

X-XSS-Protection is obsolete (modern browsers ignore it, and its filter caused vulnerabilities in old ones). The default content-type also means a response with no explicit type is labeled text/plain.

A small Shelf middleware can add a consistent set, while still letting a handler override a header. This example also adds a request id, which is useful in logs and in error reports from clients:

import 'dart:io';
import 'dart:math';

import 'package:http/http.dart' as http;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

const securityHeaders = {
  'strict-transport-security': 'max-age=63072000; includeSubDomains',
  'x-content-type-options': 'nosniff',
  'x-frame-options': 'DENY',
  'referrer-policy': 'strict-origin-when-cross-origin',
  'content-security-policy': "default-src 'self'; frame-ancestors 'none'",
  'permissions-policy': 'camera=(), microphone=(), geolocation=()',
};

/// Adds security headers to every response, unless the handler set its own.
Middleware addSecurityHeaders() => (Handler inner) => (Request request) async {
      final response = await inner(request);
      return response.change(headers: {
        for (final MapEntry(:key, :value) in securityHeaders.entries)
          if (!response.headers.containsKey(key)) key: value,
      });
    };

final _random = Random.secure();

/// Reuses the caller's X-Request-Id or makes a new one, and echoes it back.
Middleware requestId() => (Handler inner) => (Request request) async {
      final id = request.headers['x-request-id'] ??
          List.generate(8, (_) => _random.nextInt(16).toRadixString(16))
              .join();
      final response =
          await inner(request.change(context: {'requestId': id}));
      return response.change(headers: {'x-request-id': id});
    };

Future<void> main() async {
  final handler = const Pipeline()
      .addMiddleware(requestId())
      .addMiddleware(addSecurityHeaders())
      .addHandler((request) => Response.ok(
          'request ${request.context['requestId']}',
          headers: {'x-frame-options': 'SAMEORIGIN'}));

  // poweredByHeader: null drops Shelf's "x-powered-by" header.
  final server = await shelf_io.serve(
      handler, InternetAddress.loopbackIPv4, 0,
      poweredByHeader: null);
  // Remove the defaults that dart:io adds to every response.
  server.defaultResponseHeaders.clear();

  final response = await http.get(
      Uri.parse('http://localhost:${server.port}/'),
      headers: {'x-request-id': 'req-42'});
  print(response.body);
  final names = response.headers.keys.toList()..sort();
  for (final name in names) {
    print('$name: ${response.headers[name]}');
  }
  await server.close();
}

Output:

request req-42
content-length: 14
content-security-policy: default-src 'self'; frame-ancestors 'none'
date: Sat, 17 Oct 2026 20:40:33 GMT
permissions-policy: camera=(), microphone=(), geolocation=()
referrer-policy: strict-origin-when-cross-origin
strict-transport-security: max-age=63072000; includeSubDomains
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-request-id: req-42

The handler's x-frame-options: SAMEORIGIN won over the middleware's DENY. Also note there's no content-type anymore: after clearing the defaults, set it explicitly on every response. x-powered-by is gone too; there's no reason to tell attackers what your server runs.

In production, accepting the caller's X-Request-Id as is lets clients put anything into your logs. Limit its length and allowed characters, or only accept it from your own proxies.

JavaScript in a browser can read only a few "safelisted" response headers from a cross-origin API. To let it read x-request-id or a pagination header like x-total-count, list it in Access-Control-Expose-Headers. That and the other Access-Control-* headers are covered in CORS. For a broader overview see Application security.

Headers added by proxies

Behind a reverse proxy or load balancer (nginx, Caddy, a cloud load balancer), the TCP connection comes from the proxy, not the user. Proxies pass the original information in headers:

Header Meaning
X-Forwarded-For: 198.51.100.7, 10.0.0.2 client address, then each proxy along the way
X-Forwarded-Proto: https scheme the client used
X-Forwarded-Host: example.com Host the client sent
Forwarded: for=198.51.100.7;proto=https the standard (RFC 7239) form of all three

Anyone can send these headers, so trust them only when the connection comes from your proxy. Each proxy appends to X-Forwarded-For, so the trustworthy entries are on the right. Walk from the right and stop at the first address that isn't one of yours:

import 'dart:io';

import 'package:shelf/shelf.dart';

/// Addresses of reverse proxies whose X-Forwarded-For we trust.
const trustedProxies = {'127.0.0.1', '10.0.0.5'};

/// The real client address. Walks X-Forwarded-For from the right and stops
/// at the first address that isn't one of our proxies.
String clientIp(Request request) {
  final info =
      request.context['shelf.io.connection_info'] as HttpConnectionInfo?;
  final peer = info?.remoteAddress.address ?? 'unknown';
  if (!trustedProxies.contains(peer)) return peer; // header can't be trusted

  final forwarded = request.headers['x-forwarded-for'];
  if (forwarded == null) return peer;
  final hops = forwarded.split(',').map((s) => s.trim()).toList();
  for (final hop in hops.reversed) {
    if (!trustedProxies.contains(hop)) return hop;
  }
  return hops.first;
}

/// A fake connection, so the example runs without a server.
class FakeInfo implements HttpConnectionInfo {
  FakeInfo(String ip) : remoteAddress = InternetAddress(ip);
  @override
  final InternetAddress remoteAddress;
  @override
  int get remotePort => 50000;
  @override
  int get localPort => 8443;
}

void main() {
  Request make(String peer, String? xff) => Request(
        'GET',
        Uri.parse('http://localhost/'),
        headers: {if (xff != null) 'x-forwarded-for': xff},
        context: {'shelf.io.connection_info': FakeInfo(peer)},
      );

  // Direct connection, no proxy.
  print(clientIp(make('203.0.113.9', null)));
  // A client tries to spoof the header without going through the proxy.
  print(clientIp(make('203.0.113.9', '1.2.3.4')));
  // Through our proxy.
  print(clientIp(make('10.0.0.5', '198.51.100.7')));
  // Through our proxy, with a spoofed value prepended by the client.
  print(clientIp(make('10.0.0.5', '1.2.3.4, 198.51.100.7')));
}

Output:

203.0.113.9
203.0.113.9
198.51.100.7
198.51.100.7

shelf_io puts the HttpConnectionInfo of the socket into request.context['shelf.io.connection_info']. With plain dart:io, use request.connectionInfo. A correct client address matters for rate limiting (see HTTP middleware) and for logs.

Common mistakes

Summary

Task Code
Header name constants HttpHeaders.contentTypeHeader, HttpHeaders.cacheControlHeader, ...
Read one value (dart:io) request.headers.value('x-api-key')
Read all values (dart:io) request.headers['x-tag']
Set / add (dart:io) response.headers.set(name, v) / .add(name, v)
Content type (dart:io) response.headers.contentType = ContentType.json
Remove server defaults server.defaultResponseHeaders.clear()
Send headers (package:http) http.get(url, headers: {'accept': 'application/json'})
Read repeated headers (package:http) response.headersSplitValues['set-cookie']
Read headers (Shelf) request.headers['accept'], request.headersAll[...]
Send repeated headers (Shelf) Response.ok(body, headers: {'x-tag': ['a', 'b']})
Add headers (Shelf) response.change(headers: {...})
Parse a Content-Type ContentType.parse(value).mimeType
Parse value; a=b HeaderValue.parse(value).parameters
HTTP dates HttpDate.format(dt.toUtc()), HttpDate.parse(s)
Conditional GET ETag + If-None-Match, return Response.notModified()
Allow cross-origin reads Access-Control-* headers, see CORS

Related articles: An HTTP server for HttpServer basics, Cookies for Cookie and Set-Cookie, CORS for cross-origin headers, HTTP middleware for applying headers across all routes, and TLS and HTTPS for serving over HTTPS, which Strict-Transport-Security requires.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents