0

Set user profile image

by
Published Apr 8, 2025

Update a user's profile image

Script clerk Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Clerk = {
3
  apiKey: string;
4
};
5
type Base64 = string;
6
/**
7
 * Set user profile image
8
 * Update a user's profile image
9
 */
10
export async function main(
11
  auth: Clerk,
12
  user_id: string,
13
  body: {
14
    file?: {
15
      base64: Base64;
16
      type:
17
        | "image/png"
18
        | "image/jpeg"
19
        | "image/gif"
20
        | "application/pdf"
21
        | "appication/json"
22
        | "text/csv"
23
        | "text/plain"
24
        | "audio/mpeg"
25
        | "audio/wav"
26
        | "video/mp4";
27
      name: string;
28
    };
29
  },
30
) {
31
  const url = new URL(
32
    `https://api.clerk.com/v1/users/${user_id}/profile_image`,
33
  );
34

35
  const formData = new FormData();
36
  for (const [k, v] of Object.entries(body)) {
37
    if (v !== undefined) {
38
      if (["file"].includes(k)) {
39
        const { base64, type, name } = v as {
40
          base64: Base64;
41
          type: string;
42
          name: string;
43
        };
44
        formData.append(
45
          k,
46
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
47
            type,
48
          }),
49
          name,
50
        );
51
      } else {
52
        formData.append(k, String(v));
53
      }
54
    }
55
  }
56
  const response = await fetch(url, {
57
    method: "POST",
58
    headers: {
59
      Authorization: "Bearer " + auth.apiKey,
60
    },
61
    body: formData,
62
  });
63
  if (!response.ok) {
64
    const text = await response.text();
65
    throw new Error(`${response.status} ${text}`);
66
  }
67
  return await response.json();
68
}
69