Moderate profile pictures

Let users upload a profile picture from your app, show it everywhere as a small square thumbnail once it's allowed, and show a fallback avatar while it's checked or if it's blocked. Profile pictures appear next to everything a user does, so only an allowed or limited picture is shown to other people.

1. Create an upload preset for avatars

In Portal › Upload presets, create a preset for profile pictures that accepts uploads with a token from your server, accepts image/* up to the size you allow, uses public visibility, keeps content after moderation and shows the decision to the uploader. A separate preset keeps avatars in their own folder with their own limits. Upload presets explains each setting.

2. Create an avatar lens

A lens is a named CDN transform. In Portal › Lenses, create one with the identifier avatar and the transform options fit=cover, width=256 and height=256, or create it from code with client.ensureLens(). Each picture is resized once and the result is reused; see Lenses and transforms for the options and billing.

Request the lens on the rendered resource, which serves each browser the best format it accepts and also converts HEIC photos from phones:

https://cdn.calmlens.com/v1/assets/{projectId}/{assetId}/rendered/@avatar

3. Sign a token for each new picture

Add an endpoint that checks the signed-in user and signs an upload token with client.uploadTokens.sign({ uploadPresetId, externalId, expiresIn }). Because the avatar preset uses public visibility, sign with an API key that can create and share assets in the preset's folder (assets:create and assets:share); a token from a key without them fails every upload with 401 upload-token/invalid. Set externalId to a new ID for each upload that names the user, such as avatar-<user ID>-<upload ID>. An externalId can belong to only one asset in a project, so a user's second picture needs a new one.

const { token, expiresAt } = await client.uploadTokens.sign({
  uploadPresetId: "preset_4Lk8Qw2Xm9Rt5Vb3Nc7P",
  externalId: "post-42",
  expiresIn: 600,
});

Before signing, save a pending upload record with the token's externalId and mark it as the user's latest upload, so a webhook that arrives early can find it. Return { token } from the endpoint. Each token uploads one file; see Upload tokens.

4. Upload from the profile page

Add the SDK's upload widget, pointed at the avatar preset and your avatar token endpoint. It uploads the picture, shows the uploader when it's checked, allowed or blocked, and gives your app the asset ID:

import { type CalmLensUpload, CalmLensUploader } from "calmlens/react";

export function PhotoUploader({ onUploaded }: { onUploaded: (upload: CalmLensUpload) => void }) {
  return (
    <CalmLensUploader
      uploadPresetId="preset_4Lk8Qw2Xm9Rt5Vb3Nc7P"
      tokenUrl="/api/upload-token"
      accept="image/*"
      maxFileSize={10 * 1024 * 1024}
      onUploaded={onUploaded}
    />
  );
}

Set capture="user" to offer the front camera on phones. Upload widget covers its other options.

Send the asset ID to your server. Retrieve the asset with client.assets.retrieve({ assetId }), check that its externalId is one you signed for this user, and save its ID and status on the pending record. Make it the user's avatar only if it is still their latest upload and is allowed or limited. Keep the previous picture until that happens, so the user isn't left without one while it's checked.

5. Update the picture from webhooks

Subscribe a webhook in Portal › Webhooks & connectors to asset.allowed, asset.limited, asset.age-restricted, asset.blocked, asset.purged and asset.failed, and match each event's externalId to the specific upload record owned by the user:

import { CalmLensError, parseWebhookEvent } from "calmlens/server";

const STATUS_EVENTS = new Set(["asset.allowed", "asset.limited", "asset.age-restricted", "asset.blocked", "asset.purged"]);

export async function POST(request: Request): Promise<Response> {
  let event;
  try {
    event = await parseWebhookEvent({
      payload: await request.text(), headers: request.headers,
      secret: (process.env.CALMLENS_WEBHOOK_SECRET ?? ""),
    });
  } catch (error) {
    if (CalmLensError.isCalmLensError(error)) return new Response(null, { status: 401 });
    throw error;
  }

  const asset = event.asset;
  if (asset?.externalId && STATUS_EVENTS.has(event.type)) {
    // Apply only to this upload/version; reject stale events in your database.
    await updateModerationStatus(asset.externalId, asset.classification.moderation.status, event.createdAt);
  } else if (asset?.externalId && event.type === "asset.failed") {
    await markModerationFailed(asset.externalId);
  }
  return new Response(null, { status: 204 });
}

When an allowed or limited event arrives, make that upload the avatar only if it is still the user's latest upload. Check and update in one transaction, so an older upload that finishes late can't replace a newer one. Events for older uploads still update their own records but never make them the avatar again. Delete a replaced asset only after the new avatar is saved. If a reviewer later blocks or purges the current avatar, the stored status changes and the fallback appears; see Status changes after publishing.

6. Render the avatar with a fallback

Show the lens image only when the stored status is allowed or limited, and the user's initial otherwise. The image also falls back if the CDN refuses it, for example after a status change your page hasn't loaded yet.

import { CalmLensAppClient } from "calmlens/app";
import { useState } from "react";

// Builds public CDN URLs without a request or an API key.
const calmlens = new CalmLensAppClient({ uploadPresetId: "preset_4Lk8Qw2Xm9Rt5Vb3Nc7P" });

type AvatarProps = { projectId: string; assetId?: string; status?: string; name: string };

export function Avatar({ projectId, assetId, status, name }: AvatarProps) {
  const [failed, setFailed] = useState(false);
  if (!assetId || (status !== "allowed" && status !== "limited") || failed) {
    return (
      <span className="avatar" role="img" aria-label={name}>
        {name.charAt(0).toUpperCase()}
      </span>
    );
  }
  const src = calmlens.cdn.getAssetUrl({
    projectId,
    assetId,
    resource: "rendered",
    lens: "avatar",
  });
  return <img className="avatar" src={src} alt={name} onError={() => setFailed(true)} />;
}
StatusThe userEveryone else
pendingTheir previous picture, and a local preview marked as being checkedTheir previous picture or the fallback
allowed or limitedThe pictureThe picture
age-restrictedA message asking for a different pictureThe fallback
blocked or purgedA message that the picture can't be usedThe fallback

Profile pictures appear in places where a reveal control doesn't fit, so treat age-restricted pictures as not shown. For images that should stay visible to some viewers, see Show sensitive media. Using the decision is the reference for each status.

7. Test it

Upload the test input images for your project as profile pictures to check the fallback, the uploader's messages and your webhook without real harmful content.

Last updated

Signing in

Signing out

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies