Bearer token authentication is the most common auth scheme for modern APIs. The client includes a token — usually obtained by logging in or through an OAuth flow — in the Authorization header of every request. The server checks this token to verify who you are. The header format is Authorization: Bearer <token>.
HttpClientRequest.bearerToken() sets this header for you.
In the example below, we first log in to get an access token, then use that token to fetch the authenticated user’s profile.
import { FetchHttpClient, HttpClient, HttpClientRequest,} from "effect/unstable/http";import { Effect } from "effect";
function fetchAuthenticatedUser() { return Effect.gen(function* () { const client = yield* HttpClient.HttpClient;
// Step 1: Log in to get a token const loginRequest = HttpClientRequest.post( "https://dummyjson.com/auth/login", ).pipe( HttpClientRequest.bodyJsonUnsafe({ username: "emilys", password: "emilyspass", }), );
const loginResponse = yield* client.execute(loginRequest); const { accessToken } = yield* loginResponse.json;
// Step 2: Use the token to fetch the current user's profile const meRequest = HttpClientRequest.get( "https://dummyjson.com/auth/me", ).pipe(HttpClientRequest.bearerToken(accessToken));
const meResponse = yield* client.execute(meRequest); const user = yield* meResponse.json;
return user; }).pipe(Effect.provide(FetchHttpClient.layer));}
// Test itEffect.runPromise(fetchAuthenticatedUser()).then((user) => { console.log("Authenticated user:", user.firstName, user.lastName); console.log("Email:", user.email);});Output:
Authenticated user: Emily JohnsonEmail: emily.johnson@x.dummyjson.com