Setting a Base URL

Avatar of Hemanta SundarayHemanta Sundaray

A common need when working with APIs is setting a base URL so you don’t repeat the full domain in every request. You can do this by customizing the client with HttpClient.mapRequest and HttpClientRequest.prependUrl.

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function fetchFromApi() {
return Effect.gen(function* () {
// Create a client with a base URL baked in
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.mapRequest(
HttpClientRequest.prependUrl("https://dummyjson.com"),
),
);
// Now all requests are relative to the base URL
const usersResponse = yield* client.get("/users/1");
const user = yield* usersResponse.json;
const productsResponse = yield* client.get("/products/1");
const product = yield* productsResponse.json;
return { user, product };
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(fetchFromApi()).then(({ user, product }) => {
console.log("User:", user.firstName, user.lastName);
console.log("Product:", product.title, `- $${product.price}`);
});

Output:

Terminal
User: Emily Johnson
Product: Essence Mascara Lash Princess - $9.99

In the example above, we create a client with a base URL baked in using mapRequest and prependUrl. Every request made through this client only needs a relative path. "/users/1" becomes "https://dummyjson.com/users/1" automatically.

Sign in to save progress

Stay in the loop

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