Upload with your server
Add a file field that sends photos to your own API, which uploads each one to CalmLens with your API key, tells the uploader whether their photo was accepted, and publishes only what is allowed. Your server sees every file and decides which record it belongs to, and your API key never reaches the browser. For a static site or public form with no backend, upload without a server.
1. Add an upload endpoint
Add an endpoint that checks the signed-in user, creates a record for the photo (for example a draft post), and uploads the file from the request body with client.assets.create(). Set externalId to the record's ID: CalmLens stores it on the asset and sends it back in every webhook. An externalId can belong to only one asset in a project, so create a new record for each upload.
const asset = await client.assets.create({
name: file.name,
content: { data: file, type: file.type }, // a File or Blob; base64 and buffers also work
externalId: `post-${post.id}`,
});
// asset.classification.status is "processing"; save asset.id with the post
Return { assetId, status } to the browser, using the asset's id and classification.moderation.status; the widget in step 2 reads these fields. Set processingOptions.keepContentAfterProcessing to serve the photo from the CDN later; without it, the file is deleted once it's moderated and its record and report remain.
Add a second endpoint that returns an upload's current status, read with client.assets.retrieve({ assetId }), so the field can show the decision once moderation finishes. It returns { status }. Check that the asset belongs to the signed-in user's record before answering.
Files pass through your server, so its own request size limit applies as well as CalmLens's. For large files, upload in parts; see Multipart uploads.
2. Add the upload widget
Install calmlens in your front end and add the SDK's upload widget with an upload function that sends each file to your endpoint, and a checkStatus function that asks your status endpoint. For each file, the widget shows the bytes sent, checks the upload until it has a decision and shows that decision to the uploader, with retries for failed uploads:
import {
type CalmLensUpload,
CalmLensUploader,
type CustomUploadContext,
createProgressFetch,
} from "calmlens/react";
// Your server stores the file with CalmLensServerClient and answers with the asset.
async function uploadPhoto(file: File, { signal, onProgress }: CustomUploadContext) {
const send = createProgressFetch(onProgress);
const response = await send("/api/photos", {
method: "POST",
headers: { "Content-Type": file.type, "X-File-Name": encodeURIComponent(file.name) },
body: file,
signal,
});
if (!response.ok) throw new Error(`Upload failed (${response.status})`);
const { assetId, status } = await response.json();
return { assetId, status };
}
async function checkPhoto(assetId: string, { signal }: { signal: AbortSignal }) {
const response = await fetch(`/api/photos/${assetId}`, { signal });
return (await response.json()).status;
}
export function OwnApiUploader({ onUploaded }: { onUploaded: (upload: CalmLensUpload) => void }) {
return (
<CalmLensUploader
upload={uploadPhoto}
checkStatus={checkPhoto}
accept="image/*"
onUploaded={onUploaded}
/>
);
}
createProgressFetch(onProgress) returns a fetch that reports the bytes sent. onUploaded receives { assetId, status, file } once a file is uploaded and wasn't blocked or purged, and again with the new status when a pending file is checked later. Throw an error to show the file as failed; a CalmLensError shows the message for its code, so your API's error codes can have their own messages. Upload widget covers several files, uploading when the form is submitted, translations and styling.
To design the field yourself, useCalmLensUpload (React, React Native and Vue) or createUploadController runs the same upload queue with the same two functions, and you render its files and statuses.
3. Save the asset ID with the post
When the uploader submits the form, send the asset ID with it. On your server, check that the asset is the one your upload endpoint created for this user's draft, so a user can't attach someone else's upload, then store the asset ID and its moderation status with the post.
The status in the browser is only for the uploader's feedback. Users can change what their browser sends, so publish from the status your server reads from CalmLens.
4. Receive the decision on your server
In Portal › Webhooks & connectors, subscribe your endpoint to asset.allowed, asset.limited, asset.age-restricted, asset.blocked, asset.purged and asset.failed. Each event carries the asset's externalId and current status, so the handler can update the post without another request:
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 });
}
The same events arrive when a reviewer changes the decision later, with the event's actor.type set to user. Store the status from each one; Status changes after publishing covers what changes for delivery. See Webhooks for setup, signatures and retries.
5. Render each status
Show the post according to the stored status. The uploader sees more than everyone else:
| Status | Uploader | Everyone else |
|---|---|---|
| pending | The photo, marked as being checked | Nothing |
| allowed | The photo | The photo |
| limited | The photo | The photo, left out of recommendations and notifications |
| age-restricted | The photo, marked as age-restricted | The photo for viewers your app allows, the placeholder for everyone else |
| blocked | An explanation that it can't be posted | Nothing |
| purged | An explanation that it was removed | Nothing |
While a photo is pending, the CDN may already serve it, so show the uploader a local preview of their file instead of a CDN URL. Using the decision is the reference for each status, Show sensitive media builds the age-restricted case, and Delivering assets covers CDN URLs.
Every project serves jurisdictions with regional rules, so apply the viewer-specific delivery action as well as the stored base status. This also applies when you render text or serve files from your own storage.
6. Test every outcome
Upload the test input images for your project to see the field and your webhook handle blocked and age-restricted photos without uploading real harmful content.