Bearer Token Authentication

Avatar of Hemanta SundarayHemanta Sundaray

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.

http.ts
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 it
Effect.runPromise(fetchAuthenticatedUser()).then((user) => {
console.log("Authenticated user:", user.firstName, user.lastName);
console.log("Email:", user.email);
});

Output:

Terminal
Authenticated user: Emily Johnson
Email: emily.johnson@x.dummyjson.com

bearerToken(token) is equivalent to setHeader("authorization", "Bearer " + token). It handles the formatting for you and keeps your code readable.

Sign in to save progress

Stay in the loop

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