Validating Response Headers

Avatar of Hemanta SundarayHemanta Sundaray

Some APIs return important metadata in response headers — pagination cursors, rate limit info, or cache tokens. You can validate these headers with HttpClientResponse.schemaHeaders().

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";
import { Effect, Schema } from "effect";
// Define a schema for headers we care about
const ResponseHeaders = Schema.Struct({
"content-type": Schema.String,
"cache-control": Schema.String,
});
function fetchAndInspectHeaders() {
return Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const request = HttpClientRequest.get("https://dummyjson.com/products/1");
const response = yield* client.execute(request);
// Validate response headers against our schema
const headers =
yield* HttpClientResponse.schemaHeaders(ResponseHeaders)(response);
console.log("Content-Type:", headers["content-type"]);
console.log("Cache-Control:", headers["cache-control"]);
const product = yield* response.json;
return product;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(fetchAndInspectHeaders()).then((product) => {
console.log("Product:", product.title);
});

Output:

Terminal
Content-Type: application/json; charset=utf-8
Cache-Control: no-store
Product: Essence Mascara Lash Princess

schemaHeaders works just like schemaBodyJson, but operates on the response headers instead of the body. You define a schema for the header keys you expect, and it validates them. If a declared header is missing or doesn’t match, you get a SchemaError.

Note that header names are always lowercased when accessed through schemaHeaders, so use lowercase keys in your schema (e.g., "content-type", not "Content-Type"). This is because the HTTP specification treats header names as case-insensitive, and Effect normalizes them to lowercase for consistency.

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.