Cookie-free API authentication
An API must accept Authorization bearer tokens because it does not support browser cookies.
Better Auth · Function
The Bearer plugin authenticates API requests with bearer tokens instead of browser cookies. It supports automatic or per-request token attachment and server-side session retrieval.
The Bearer plugin lets API clients authenticate without browser cookies. It makes a token available after sign-in, and clients can attach that token globally or per request through the Authorization Bearer header; server-side session lookup can then authenticate the request.
bearer()The plugin configures bearer-token authentication; authenticated sign-in responses provide a session token in response headers.
import { betterAuth } from "better-auth";
import { bearer } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [bearer()]
});
const response = await fetch("/api/auth/sign-in/email", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email, password })
});
const token = response.headers.get("set-auth-token");
await fetch("/api/private", {
headers: { Authorization: `Bearer ${token}` }
});Enable the plugin, obtain the session token returned after sign-in, and send it in the Authorization header for API requests.
An API must accept Authorization bearer tokens because it does not support browser cookies.
A client makes repeated API calls and should attach one stored session token automatically.
A non-Better-Auth HTTP client needs to call a protected endpoint.
The Bearer plugin enables authentication with bearer tokens instead of browser cookies. Add bearer() to the Better Auth plugins array, then send the resulting token in the Authorization header.
Follow-up: How can a client attach the token automatically? Configure the auth client's fetchOptions.auth with type set to Bearer and a token callback that returns the stored token.
After a successful sign-in, the response contains a session token in its headers. The client can store that token securely and use it in subsequent API requests.
Follow-up: How can a token be limited to one request? Put an Authorization header containing Bearer followed by the token in that request's fetchOptions.
The server can authenticate a bearer-token request with auth.api.getSession. The request must include the Authorization Bearer header for session lookup to work.
Follow-up: Why might this plugin be inappropriate for a browser application? Browser-cookie authentication may be preferable when the API already supports cookies, avoiding unnecessary token handling.
auth.api.getSessioncreateAuthClientfetchOptions.authAuthorizationJWT plugin