Setting a Single Header

Avatar of Hemanta SundarayHemanta Sundaray

To set a single header on request, use HttpClientRequest.setHeader().

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.setHeader("X-Request-Source", "effect-course"),
);
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

In the example above, we add a custom X-Request-Source header to our request.

setHeader takes a key and a value, both strings. It appends the header to the request. If the header already exists, it replaces the previous value.

Sign in to save progress

Stay in the loop

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