getAccessToken
Complete API reference for the api.getAccessToken method, providing type-safe OAuth access token retrieval across all runtimes.
The api.getAccessToken method is the primary programmatic entry point for retrieving the OAuth access token for a specific provider. This method runs on the server, so it requires you to pass the request or headers object from your server-side context.
import { api } from "@/lib/auth"
const output = await api.getAccessToken("github", {
request: getRequest(),
})This method is a simplified version of api.getProviderTokens, which retrieves the full set of OAuth tokens (access token,
refresh token, and ID token) for a provider. Use this method if you only need the access token. See
api.getProviderTokens for the advanced alternative.
Reference
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| providerId | string | Yes | The id of the OAuth provider to retrieve the access token for. |
| options | AccessTokenAPIOptions | Yes | An object containing request context. |
AccessTokenAPIOptions
| Option | Type | Default | Description |
|---|---|---|---|
| request | Request | undefined | The request object from the server-side context. |
| headers | Headers | undefined | The headers object from the server-side context. |
| skipCSRFCheck | boolean | false | Whether to skip CSRF token verification for this request. |
At least one of request or headers is required to construct the incoming URL and validate redirect URLs.
Returns
| Return Type | Description |
|---|---|
Promise<AccessTokenAPIReturn> | Resolves to an object containing success and accessToken — see Behavior. |
Behavior
- This function internally uses
api.getProviderTokensto retrieve the access token for the specified provider. Seeapi.getProviderTokensfor the full retrieval/refresh behavior. - CSRF protection is verified by default. Set
skipCSRFCheck: trueonly if you're enforcing CSRF protection at a different layer (e.g. a framework-level middleware) — disabling it here without an equivalent safeguard reintroduces the vulnerability it protects against. - If retrieval fails (no valid access or refresh token for the provider),
accessTokenresolves tonullandsuccessisfalse.
Usage
Get a provider's access token
import { api } from "@/lib/auth"
const { success, accessToken } = await api.getAccessToken("github", {
request: getRequest(),
})Using the token in a request
import { api } from "@/lib/auth"
const { success, accessToken } = await api.getAccessToken("github", {
request: getRequest(),
})
if (!success) {
redirect("/login")
}
const response = await fetch("/api/some-protected-route", {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})Delegating CSRF protection to a different layer
import { api } from "@/lib/auth"
const { success, accessToken } = await api.getAccessToken("github", {
request: getRequest(),
skipCSRFCheck: true, // only if enforced elsewhere — see the warning above
})