Using HttpClientRequest

Avatar of Hemanta SundarayHemanta Sundaray

For more control over your requests, you can use HttpClientRequest to build a request object first, then execute it.

This is the pattern we’ll use throughout the rest of this course because it composes better and gives you more flexibility.

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function fetchUserWithRequest(userId: number) {
return Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
// Step 1: Create a request object
const request = HttpClientRequest.get(
`https://dummyjson.com/users/${userId}`,
);
// Step 2: Execute the request
const response = yield* client.execute(request);
// Step 3: Parse the response
const user = yield* response.json;
return user;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(fetchUserWithRequest(3)).then((user) => {
console.log("Name:", user.firstName, user.lastName);
});

The HttpClientRequest pattern separates request creation from execution:

  1. Create: HttpClientRequest.get(url) creates a request object.
  2. Modify(optional): Add headers, URL parameters, a request body, and more using .pipe(). In the example above, we don’t customize the request, but you’ll see plenty of examples in the upcoming chapters.
  3. Execute: client.execute(request) sends the request.

Output:

Terminal
Name: Sophia Brown

Sign in to save progress

Stay in the loop

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