0

Create a new organization membership

by
Published Apr 8, 2025

Adds a user as a member to the given organization. Only users in the same instance as the organization can be added as members. This organization will be the user's [active organization] (https://clerk.com/docs/organizations/overview#active-organization) the next time they create a session, presuming they don't explicitly set a different organization as active before then.

Script clerk Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Clerk = {
3
  apiKey: string;
4
};
5
/**
6
 * Create a new organization membership
7
 * Adds a user as a member to the given organization.
8
Only users in the same instance as the organization can be added as members.
9

10
This organization will be the user's [active organization] (https://clerk.com/docs/organizations/overview#active-organization)
11
the next time they create a session, presuming they don't explicitly set a
12
different organization as active before then.
13
 */
14
export async function main(
15
  auth: Clerk,
16
  organization_id: string,
17
  body: { user_id: string; role: string },
18
) {
19
  const url = new URL(
20
    `https://api.clerk.com/v1/organizations/${organization_id}/memberships`,
21
  );
22

23
  const response = await fetch(url, {
24
    method: "POST",
25
    headers: {
26
      "Content-Type": "application/json",
27
      Authorization: "Bearer " + auth.apiKey,
28
    },
29
    body: JSON.stringify(body),
30
  });
31
  if (!response.ok) {
32
    const text = await response.text();
33
    throw new Error(`${response.status} ${text}`);
34
  }
35
  return await response.json();
36
}
37