0

List all sessions

by
Published Apr 8, 2025

Returns a list of all sessions. The sessions are returned sorted by creation date, with the newest sessions appearing first. **Deprecation Notice (2024-01-01):** All parameters were initially considered optional, however moving forward at least one of `client_id` or `user_id` parameters should be provided.

Script clerk Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Clerk = {
3
  apiKey: string;
4
};
5
/**
6
 * List all sessions
7
 * Returns a list of all sessions.
8
The sessions are returned sorted by creation date, with the newest sessions appearing first.
9
**Deprecation Notice (2024-01-01):** All parameters were initially considered optional, however
10
moving forward at least one of `client_id` or `user_id` parameters should be provided.
11
 */
12
export async function main(
13
  auth: Clerk,
14
  client_id: string | undefined,
15
  user_id: string | undefined,
16
  status:
17
    | "abandoned"
18
    | "active"
19
    | "ended"
20
    | "expired"
21
    | "removed"
22
    | "replaced"
23
    | "revoked"
24
    | undefined,
25
  limit: string | undefined,
26
  offset: string | undefined,
27
) {
28
  const url = new URL(`https://api.clerk.com/v1/sessions`);
29
  for (const [k, v] of [
30
    ["client_id", client_id],
31
    ["user_id", user_id],
32
    ["status", status],
33
    ["limit", limit],
34
    ["offset", offset],
35
  ]) {
36
    if (v !== undefined && v !== "" && k !== undefined) {
37
      url.searchParams.append(k, v);
38
    }
39
  }
40
  const response = await fetch(url, {
41
    method: "GET",
42
    headers: {
43
      Authorization: "Bearer " + auth.apiKey,
44
    },
45
    body: undefined,
46
  });
47
  if (!response.ok) {
48
    const text = await response.text();
49
    throw new Error(`${response.status} ${text}`);
50
  }
51
  return await response.json();
52
}
53