Next.js
A Next.js (App Router) app with two server route handlers and a page that embeds the hosted capture page. The API key and the CorrelationId stay on the server. Shown with Next.js 14.
| File | What it does |
|---|---|
lib/screenlyyid.js | Server-only helpers: the two ScreenlyyID calls and the in-memory session store. |
app/api/verifications/route.js | POST: Step 1, calls instance/create. |
app/api/verifications/[id]/route.js | GET: Step 4, reads the result once with document/result. |
app/page.js | The page: starts a verification, embeds the hosted page in an iframe, listens for IDV_SESSION_COMPLETE. |
Setup#
Add a path alias for @/ in jsconfig.json, and put a test key in .env.local (never commit it). See Get a test key.
{ "compilerOptions": { "paths": { "@/*": ["./*"] } } }# .env.local
SCREENLYYID_API_KEY=test_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxlib/screenlyyid.js#
// Server-only helpers. The API key and the CorrelationId never reach the browser.
const API = "https://api.screenlyyid.com";
// verificationId -> { userId, correlationId }. In memory for the example; use your database.
// (A module-level Map is shared per server process; with several instances or serverless functions, use a database.)
const globalStore = globalThis;
export const sessions = (globalStore.__sessions ??= new Map());
export function apiKey() {
const key = process.env.SCREENLYYID_API_KEY; // a test_ key while you build
if (!key) throw new Error("SCREENLYYID_API_KEY is not set");
return key;
}
export async function createInstance() {
const r = await fetch(`${API}/api/v1/instance/create`, {
method: "POST",
headers: { "x-api-key": apiKey(), "Content-Type": "application/json" },
body: JSON.stringify({ GlobalScreening: ["idv"], CustomerIntelligence: [] }),
cache: "no-store",
});
if (!r.ok) throw new Error(`ScreenlyyID instance/create failed (HTTP ${r.status})`);
return r.json(); // { CorrelationId, webEnrolmentUrl }: the property names are exactly these
}
export function getResult(correlationId) {
return fetch(`${API}/api/v1/document/result`, {
headers: { "x-api-key": apiKey(), "x-correlation-id": correlationId },
cache: "no-store",
});
}app/api/verifications/route.js#
import { randomUUID } from "node:crypto";
import { createInstance, sessions } from "@/lib/screenlyyid";
export const dynamic = "force-dynamic";
// Step 1: create a verification session (server side).
export async function POST() {
const userId = "demo-user"; // replace with your own authentication
try {
const { CorrelationId, webEnrolmentUrl } = await createInstance();
const verificationId = randomUUID();
sessions.set(verificationId, { userId, correlationId: CorrelationId });
return Response.json({ verificationId, webEnrolmentUrl }, { status: 201 }); // no CorrelationId
} catch (e) {
return Response.json({ error: e.message }, { status: 502 });
}
}app/api/verifications/[id]/route.js#
import { getResult, sessions } from "@/lib/screenlyyid";
export const dynamic = "force-dynamic";
// Step 4: after the browser reports IDV_SESSION_COMPLETE, read the result once.
export async function GET(_request, { params }) {
const userId = "demo-user"; // replace with your own authentication
const session = sessions.get(params.id);
if (!session || session.userId !== userId) return Response.json({ error: "Unknown verification" }, { status: 404 });
const r = await getResult(session.correlationId);
if (r.status === 200) return Response.json({ status: "ready", result: await r.json() });
if (r.status === 500) return Response.json({ status: "pending" }); // asked before the capture finished
return Response.json({ error: `ScreenlyyID document/result failed (HTTP ${r.status})` }, { status: 502 });
}app/page.js#
"use client";
import { useEffect, useRef, useState } from "react";
export default function Page() {
const [session, setSession] = useState(null); // { verificationId, webEnrolmentUrl }
const [message, setMessage] = useState("");
const frame = useRef(null);
async function start() {
const r = await fetch("/api/verifications", { method: "POST" });
const body = await r.json();
if (!r.ok) return setMessage(body.error);
setSession(body);
}
// Step 3: the hosted page tells its parent window when it is done.
useEffect(() => {
if (!session) return;
async function onMessage(event) {
const el = frame.current;
if (!el || event.source !== el.contentWindow) return; // only the iframe we created
if (event.origin !== new URL(el.src).origin) return; // and only from the hosted page's origin
const { eventName, isError, error } = event.data || {};
if (eventName === "IDV_SESSION_COMPLETE" && !isError) {
// Step 4: ask YOUR server for the result. It reads it from ScreenlyyID once.
const r = await fetch(`/api/verifications/${session.verificationId}`);
setMessage(JSON.stringify(await r.json()));
setSession(null);
} else if (eventName === "ERROR") {
setMessage("Verification failed: " + error);
setSession(null);
}
}
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, [session]);
return (
<main>
<button onClick={start}>Verify my identity</button>
{session && (
<iframe ref={frame} src={session.webEnrolmentUrl} allow="camera; microphone"
style={{ width: "100%", height: 700, border: 0 }} title="Identity verification" />
)}
<pre>{message}</pre>
</main>
);
}The page checks that each message comes from the iframe it created and from the hosted page's origin, because the hosted page sends its messages to any origin. Treat the event only as a signal: your server reads the result.
Run and test#
npm run devcurl -s -X POST localhost:3000/api/verifications
# {"verificationId":"...","webEnrolmentUrl":"https://app.screenlyyid.com/idv/..."}
curl -s localhost:3000/api/verifications/VERIFICATION_ID
# {"status":"pending"} (asked before the person has finished the capture)Open webEnrolmentUrl in a browser or embed it as described in Web app. When the page reports IDV_SESSION_COMPLETE, the same GET returns {"status":"ready","result":{...}}.
Or open the page and press Verify my identity: the hosted capture page appears in the iframe.
On a serverless host, the in-memory sessions map is not shared between function instances: use your database.
Run it from the repo: this is the code in nextjs/ of the public examples repo (ScreenlyyID/examples), which has a README and an .env.example.
What this does not include#
- Your own sign-in. The sample uses a fixed
demo-user. Replace it with your authentication, and keep the check that a verification belongs to the person asking. - A database. Sessions are kept in memory so the sample stays short. Store the
CorrelationIdagainst your user in your database. - HTTPS and rate limits. Add both before this faces the internet.
See the AI quickstart for the full API flow and the error table.