0

Merge and update organization membership metadata

by
Published Apr 8, 2025

Update an organization membership's metadata attributes by merging existing values with the provided parameters. Metadata values will be updated via a deep merge. Deep means that any nested JSON objects will be merged as well. You can remove metadata keys at any level by setting their value to `null`.

Script clerk Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Clerk = {
3
  apiKey: string;
4
};
5
/**
6
 * Merge and update organization membership metadata
7
 * Update an organization membership's metadata attributes by merging existing values with the provided parameters.
8
Metadata values will be updated via a deep merge. Deep means that any nested JSON objects will be merged as well.
9
You can remove metadata keys at any level by setting their value to `null`.
10
 */
11
export async function main(
12
  auth: Clerk,
13
  organization_id: string,
14
  user_id: string,
15
  body: { public_metadata?: {}; private_metadata?: {} },
16
) {
17
  const url = new URL(
18
    `https://api.clerk.com/v1/organizations/${organization_id}/memberships/${user_id}/metadata`,
19
  );
20

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