0

Merge and update a user's metadata

by
Published Apr 8, 2025

Update a user's metadata attributes by merging existing values with the provided parameters. This endpoint behaves differently than the *Update a user* endpoint. Metadata values will not be replaced entirely. Instead, a deep merge will be performed. 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 a user's metadata
7
 * Update a user's metadata attributes by merging existing values with the provided parameters.
8

9
This endpoint behaves differently than the *Update a user* endpoint.
10
Metadata values will not be replaced entirely.
11
Instead, a deep merge will be performed.
12
Deep means that any nested JSON objects will be merged as well.
13

14
You can remove metadata keys at any level by setting their value to `null`.
15
 */
16
export async function main(
17
  auth: Clerk,
18
  user_id: string,
19
  body: { public_metadata?: {}; private_metadata?: {}; unsafe_metadata?: {} },
20
) {
21
  const url = new URL(`https://api.clerk.com/v1/users/${user_id}/metadata`);
22

23
  const response = await fetch(url, {
24
    method: "PATCH",
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