0

Retrieve the OAuth access token of a user

by
Published Apr 8, 2025

Fetch the corresponding OAuth access token for a user that has previously authenticated with a particular OAuth provider. For OAuth 2.0, if the access token has expired and we have a corresponding refresh token, the access token will be refreshed transparently the new one will be returned.

Script clerk Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Clerk = {
3
  apiKey: string;
4
};
5
/**
6
 * Retrieve the OAuth access token of a user
7
 * Fetch the corresponding OAuth access token for a user that has previously authenticated with a particular OAuth provider.
8
For OAuth 2.0, if the access token has expired and we have a corresponding refresh token, the access token will be refreshed transparently the new one will be returned.
9
 */
10
export async function main(auth: Clerk, user_id: string, provider: string) {
11
  const url = new URL(
12
    `https://api.clerk.com/v1/users/${user_id}/oauth_access_tokens/${provider}`,
13
  );
14

15
  const response = await fetch(url, {
16
    method: "GET",
17
    headers: {
18
      Authorization: "Bearer " + auth.apiKey,
19
    },
20
    body: undefined,
21
  });
22
  if (!response.ok) {
23
    const text = await response.text();
24
    throw new Error(`${response.status} ${text}`);
25
  }
26
  return await response.json();
27
}
28