Setting Multiple Headers

Avatar of Hemanta SundarayHemanta Sundaray

To set several headers at once, use HttpClientRequest.setHeaders().

Instead of chaining multiple setHeader calls, you pass an object with all the headers you need.

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function fetchProducts() {
return Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const request = HttpClientRequest.get(
"https://dummyjson.com/products",
).pipe(
HttpClientRequest.setUrlParam("limit", "3"),
HttpClientRequest.setHeaders({
"X-Request-Source": "effect-course",
"X-Request-Version": "1.0",
"Cache-Control": "no-cache",
}),
);
const response = yield* client.execute(request);
const data = yield* response.json;
return data;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(fetchProducts()).then((data) => {
data.products.forEach((product) => {
console.log(` - ${product.title}: $${product.price}`);
});
});

Output:

Terminal
- Essence Mascara Lash Princess: $9.99
- Eyeshadow Palette with Mirror: $19.99
- Powder Canister: $14.99

setHeaders takes an object where each key is a header name and each value is the header value. All headers are applied at once, replacing any existing headers with the same names.

Sign in to save progress

Stay in the loop

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