Most apps that need an age gate start with a date-of-birth field, then discover it stops nobody. Facial age estimation is the practical next step: the user takes a selfie, your backend sends it to an API, and you get an estimated age back in a single round trip, with no ID upload and no manual review.
This guide walks through a complete age estimation API integration using the ROC Age Estimation API as the working example, from the first request to the threshold logic and privacy handling that make it safe to ship.
By the end you will have a server-side function that accepts an image, calls the API, and returns one of three decisions: allow, ask for a retake, or step up to a stronger check. That last option matters. Age estimation is a probabilistic signal, and a well-built age gate treats it as the first layer of a process rather than the final word.
The code samples use plain HTTP, so they translate to any stack. The service behind them comes from ROC AI, a U.S. company that builds face, fingerprint and iris algorithms and reports a first-place global ranking in NIST’s age estimation evaluation, which is useful context when you need to justify your choice of provider to a compliance team.
The same integration pattern applies to most age estimation APIs, so treat the provider-specific details as an example and check them against whichever reference you use.
There are two broad ways to check a user’s age online, and it helps to be clear about which one you are building.
| Method | What the user provides | What you get back | Typical role |
|---|---|---|---|
| Age estimation | A face image | An estimated age and a quality signal | Fast first layer for most users |
| Age verification | ID document, database match or credential | A confirmed date of birth or over/under result | Fallback for borderline or high-risk cases |
Estimation keeps friction and data collection low, which is why most online age verification for apps now starts there and escalates only when needed. This tutorial builds the estimation layer and leaves a clean hook for the fallback.
Create an account in the provider’s developer portal and generate an API key. For the ROC API, the key is sent as a bearer token in the Authorization header.
Two rules apply to any age verification API tutorial worth following:
export ROC_API_KEY=”your_api_key_here”
The endpoint takes a single face image. According to the published API reference, the request is a multipart/form-data upload with one field, image, which accepts JPEG, PNG, WebP, GIF or BMP files up to 10 MB.
A quick test from the command line:
curl -X POST https://api.roc.ai/v1/face/age \
-H “Authorization: Bearer $ROC_API_KEY” \
-F “image=@selfie.jpg”
In Node.js 18 or later, fetch, FormData and Blob are built in, so no extra packages are needed:
const ROC_AGE_URL = “https://api.roc.ai/v1/face/age”;
export async function estimateAge(imageBuffer, mimeType = “image/jpeg”) {
const form = new FormData();
form.append(“image”, new Blob([imageBuffer], { type: mimeType }), “selfie”);
const res = await fetch(ROC_AGE_URL, {
method: “POST”,
headers: { Authorization: `Bearer ${process.env.ROC_API_KEY}` },
body: form,
signal: AbortSignal.timeout(10_000),
});
const requestId = res.headers.get(“x-request-id”);
const body = await res.json();
if (!res.ok) {
const err = new Error(body.message || body.error || “Age estimation failed”);
err.status = res.status;
err.requestId = requestId;
throw err;
}
return { age: body.age, quality: body.quality, requestId };
}
The Python equivalent with requests:
import os
import requests
ROC_AGE_URL = “https://api.roc.ai/v1/face/age”
def estimate_age(image_bytes: bytes, mime_type: str = “image/jpeg”) -> dict:
resp = requests.post(
ROC_AGE_URL,
headers={“Authorization”: f”Bearer {os.environ[‘ROC_API_KEY’]}”},
files={“image”: (“selfie”, image_bytes, mime_type)},
timeout=10,
)
request_id = resp.headers.get(“X-Request-Id”)
body = resp.json()
if not resp.ok:
raise RuntimeError(
f”{resp.status_code} {body.get(‘error’)}: {body.get(‘message’)} “
f”(request {request_id})”
)
return {“age”: body[“age”], “quality”: body[“quality”], “request_id”: request_id}
Pass the image bytes straight from the upload handler. There is no need to write the selfie to disk, and not doing so makes your privacy story simpler.
A successful call returns a small JSON object:
{
“age”: 35.26,
“quality”: “high”
}
The single most important design choice is what you do with the number. An estimate of 18.4 does not mean the user is an adult, because every model has an error margin, and that margin is widest right around the legal thresholds you care about.
The standard answer is a buffer. Instead of allowing anyone estimated at 18 or older, you allow users whose estimate clears the threshold by a comfortable margin and step up everyone else.
Retailers have used the same idea for years with “Challenge 25” policies, and NIST includes a Challenge-25 scenario in its age estimation evaluation for exactly this reason.
| Your legal threshold | Example buffer | Auto-allow at | Everyone below |
|---|---|---|---|
| 13 | 3 years | 16 or older | Step up or route to a teen or parental consent flow |
| 16 | 4 years | 20 or older | Step up |
| 18 | 7 years | 25 or older | Step up |
These buffers are illustrations, not recommendations. Tune them with your own test data and your legal team, and widen them for lower-quality images:
export function ageGateDecision({ age, quality }, { threshold = 18, buffer = 7 } = {}) {
if (quality === “low”) return “retake”; // ask for a better photo first
const margin = quality === “medium” ? buffer + 2 : buffer;
if (age >= threshold + margin) return “allow”;
return “step_up”; // ID check, parental consent or another method
}
Notice that the function never returns “deny.” A user estimated below the buffer may still be an adult, so the respectful default is a stronger check, not a hard block.
Real-world selfies are dark, blurry, cropped or taken at an angle. Plan for that from day one:
The API reference lists the error responses you should handle. Each error body includes an error field and may include message, reason and requestId.
| Status | What it usually means | What to do |
|---|---|---|
| 400 | The request is malformed | Check the multipart field name and file |
| 401 | Missing or invalid API key | Check the key and the Authorization header |
| 402 | Payment or plan issue, such as exhausted credits | Alert your team and fall back to another method |
| 413 | The image is too large | Resize or compress below 10 MB before sending |
| 422 | The image could not be processed | Treat it like a low-quality result and ask for a retake |
| 429 | Too many requests | Back off and retry with exponential delay |
| 500, 502, 503 | A server-side problem | Retry once, then fall back so users are not stuck |
The fallback path is what keeps your age gate available. If the estimation service is down, users should still be able to complete a document check or parental consent flow.
A face image is sensitive data even when you never identify the person, so treat it accordingly:
If your app may attract children, estimation can help you spot users who are likely under 13 and route them to a parental consent flow or an age-appropriate experience.
It does not by itself satisfy every COPPA obligation, such as obtaining verifiable parental consent, so build it as one control within a broader compliance program.
A working age gate needs four pieces: a secure server-side call, a buffer around your threshold, a retake and fallback path, and a privacy policy that matches what the code actually does.
Once those are in place, the estimation layer handles the clear-cut majority of users in seconds and leaves only the borderline cases for slower checks.
If you want to try the pattern above against real images, ROC currently gives eligible U.S. businesses 100 free production requests, which is enough to measure how your own users fall around your threshold before you commit to a plan.
The U.S. Treasury Department’s Financial Crimes Enforcement Network (FinCEN) has taken some systems offline after…
The U.S. Cybersecurity and Infrastructure Security Agency (CISA) added three flaws affecting Drupal Core, Idunno…
A Thanksgiving invitation, a Black Friday discount, or a holiday greeting may look harmless. But…
Task management app Todoist said an attacker breached its production systems on November 23, 2026,…
Switzerland’s National Cyber Security Center (NCSC) has confirmed its first cases of AI-assisted cyberattacks against…
Microsoft has fixed a Microsoft 365 startup issue that left some Windows users staring at…