Skip to main content

JavaScript SDK

The SafePassage JavaScript SDK starts a verification from your web page with your publishable key: it creates the session and takes the user to the hosted SafePassage page, either in the same tab or in a new tab or popup.

The SDK does not decide access. Everything it reports in the browser can be changed by the user, so your server must still confirm each result with your secret key before granting access. This page shows the complete flow: browser code plus the server endpoint it needs.

SDK or server integration?

If your server can create the session itself, the Server integration is simpler and needs no browser code. Use the SDK when you want to start verification from client-side code, for example in a single-page app, or open it in a popup.

Before you start​

  • A publishable key (pk_…) for the browser and a secret key (sk_…) for your server, from Dashboard → API Keys.
  • Your site's domain in Configuration → Domains (recommended). While the list is not empty, the SDK works only on pages served from those domains. Add localhost while you test locally.
  • A page served over https:// (or http://localhost for testing). Opening an HTML file directly (file://) does not work.

Install​

From the CDN:

<script src="https://cdn.jsdelivr.net/npm/@safepassage/sdk@3.5.6/sdk.min.js"></script>

Or from npm:

npm install @safepassage/sdk@3.5.6
import { SafePassage } from '@safepassage/sdk';

Pin the version as shown so that SDK updates reach your site only when you choose. The CDN bundle defines window.SafePassage.

How the flow works​

  1. Your page asks your server who the user is, so it can pass their ID as externalUserId.
  2. The user clicks a button and your page calls sdk.verify(). The SDK creates a session with your publishable key and opens the verification page.
  3. After a successful verification, the user returns to your returnUrl with ?sessionId=…&status=verified.
  4. Your page sends the sessionId to your server, which calls Validate Session with the secret key and checks that accessGranted is true and externalUserId is the signed-in user.
  5. Your server records the user as verified and serves the restricted content.

Complete example​

The example is a page plus a small Node.js server. Replace the demo sign-in with your own login.

index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Members area</title>
<script src="https://cdn.jsdelivr.net/npm/@safepassage/sdk@3.5.6/sdk.min.js"></script>
</head>
<body>
<h1>Members area</h1>
<p id="message" role="status">Checking your verification…</p>
<button id="verify" hidden>Verify my age</button>
<div id="content"></div>

<script>
const PUBLISHABLE_KEY = 'pk_your_publishable_key'; // publishable key only: never sk_
const message = document.getElementById('message');
const button = document.getElementById('verify');

function show(text, offerVerify) {
message.textContent = text;
button.hidden = !offerVerify;
button.disabled = false;
}

// Restricted content comes from your server, which only sends it to
// verified users. Hiding content in the page is not protection.
async function showContent() {
const response = await fetch('/api/members-content');
if (!response.ok) return show('Verify your age to continue.', true);
message.textContent = '';
button.hidden = true;
document.getElementById('content').innerHTML = await response.text();
}

async function init() {
if (typeof SafePassage === 'undefined') {
return show('Verification is unavailable right now. Please try again later.', false);
}
const context = await (await fetch('/api/verification/context')).json();
if (context.verified) return showContent();

// After a successful verification the user returns here with ?sessionId=…&status=verified.
// Ignore status: ask your server to confirm the session with your secret key.
const sessionId = new URLSearchParams(location.search).get('sessionId');
if (sessionId) {
history.replaceState(null, '', location.pathname);
const response = await fetch('/api/verification/confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId }),
});
const result = await response.json();
if (result.verified) return showContent();
if (result.status === 'pending') return show('Your verification is not finished. Continue when you are ready.', true);
if (!response.ok) return show('We could not confirm your verification. Please try again shortly.', true);
}

show('Verify your age to continue.', true);
const sdk = new SafePassage({
apiKey: PUBLISHABLE_KEY,
returnUrl: location.origin + location.pathname,
});
button.onclick = () => {
button.disabled = true;
// verify() navigates to the verification page. It rejects if the
// session cannot be started (network, configuration, account limits
// or too many attempts).
sdk.verify({ externalUserId: context.externalUserId }).catch((error) => {
show(/Too many verification attempts/.test(error.message)
? 'Too many attempts. Please wait a minute and try again.'
: 'We could not start verification. Please try again.', true);
});
};
}

init().catch(() => show('Something went wrong. Please reload the page.', false));
</script>
</body>
</html>
server.mjs
// server.mjs: serves the SDK page and confirms results with the secret key (Node.js 18+, Express).
// Run: npm install express && node server.mjs
import crypto from 'node:crypto';
import express from 'express';

const API_URL = 'https://api.safepassageapp.com/api/v1';
const SECRET_KEY = process.env.SAFEPASSAGE_SECRET_KEY;
if (!SECRET_KEY?.startsWith('sk_')) throw new Error('Set SAFEPASSAGE_SECRET_KEY to your secret key (sk_...)');

const verifiedUsers = new Map(); // userId -> sessionId. Use your database in production.

const app = express();
app.use(express.json());

// Demo sign-in: a random user ID in a cookie. Use your real login instead.
app.use((req, res, next) => {
const match = /(?:^|;\s*)demo_uid=([\w-]+)/.exec(req.headers.cookie || '');
req.userId = match ? match[1] : crypto.randomUUID();
if (!match) res.append('Set-Cookie', `demo_uid=${req.userId}; Path=/; HttpOnly; SameSite=Lax`);
next();
});

app.get('/', (req, res) => res.sendFile(new URL('./index.html', import.meta.url).pathname));

app.get('/api/verification/context', (req, res) => {
res.json({ verified: verifiedUsers.has(req.userId), externalUserId: req.userId });
});

// ── Confirm a session reported by the browser ────────────────────────────────
app.post('/api/verification/confirm', async (req, res) => {
const sessionId = String(req.body?.sessionId ?? '');
let status = 0;
let body = {};
try {
const response = await fetch(`${API_URL}/sessions/validate`, {
method: 'POST',
headers: { Authorization: `Bearer ${SECRET_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId }),
signal: AbortSignal.timeout(15000),
});
status = response.status;
body = await response.json().catch(() => ({}));
} catch (error) {
console.error('Session validation request failed', error.message);
}

// externalUserId ties the session to the user who started it, so a session
// can only ever verify that one user.
if (status === 200 && body.accessGranted === true && body.externalUserId === req.userId) {
verifiedUsers.set(req.userId, sessionId);
return res.json({ verified: true });
}
if (status === 200 || status === 400 || status === 404) {
// pending, cancelled, failed, expired, unknown, or another user's session
// Report another user's session as not_verified: never echo its status.
const own = status === 200 && body.externalUserId === req.userId;
return res.json({ verified: false, status: own ? body.status : 'not_verified' });
}
console.error('Session validation failed', status, body.message);
res.status(502).json({ verified: false, status: 'unavailable' });
});

// Restricted content is only ever sent to verified users.
app.get('/api/members-content', (req, res) => {
if (!verifiedUsers.has(req.userId)) return res.status(403).send('Verification required');
res.send('<p>Welcome. You are verified.</p>');
});

// ── Start the server ─────────────────────────────────────────────────────────
app.listen(3000, () => console.log('Listening on http://localhost:3000'));

To run it, put both files in one folder, set your publishable key in index.html, then:

npm install express
export SAFEPASSAGE_SECRET_KEY=sk_your_secret_key
node server.mjs # then open http://localhost:3000
You should see
  • "Verify your age to continue" and a Verify my age button.
  • After verifying, you return to the page and see "Welcome. You are verified." The content came from /api/members-content, which refuses unverified users.
  • Opening http://localhost:3000/?sessionId=00000000-0000-4000-8000-000000000000&status=verified in a new private window does not unlock anything.

To receive webhooks as well, add the webhook receiver from Server integration.

Configuration options​

const sdk = new SafePassage({
apiKey: 'pk_your_publishable_key',
returnUrl: location.origin + location.pathname,
});
OptionTypeDescription
apiKeystringRequired. Your publishable key (pk_…). The SDK refuses secret keys.
returnUrlstringRequired. Where the user returns after a successful verification. HTTPS, except http://localhost and http://127.0.0.1.
cancelUrlstringWhere the opener page goes if the user closes a new-tab verification, with status=cancelled. Also where a user who chooses Return to site before finishing is sent.
mode'redirect' or 'new-tab''redirect' (default) uses the same tab. 'new-tab' opens a popup or tab and reports through callbacks.
newTabTarget'popup' or 'tab'For mode: 'new-tab': a fixed-size popup (default) or a full tab.
languagestringForce the interface language (en, de, es, fr, pt, it). Usually omit it: the user's browser language is used.
onComplete(result) => voidNew-tab mode only. Called when the verification succeeds.
onError(error) => voidCalled when something goes wrong; see Handling problems.
onCancel() => void | falseNew-tab mode only. Called when the user closes the window before finishing. Return false to stay on the page instead of going to cancelUrl.
environment'production'Leave unset. See Environment.

verify() options:

OptionDescription
externalUserIdYour ID for the user. Returned by Validate Session; your server must check it.
skipIntrotrue skips the introduction screen.
autoReturntrue returns to your site right after success, without the success screen.
languageInterface language for this verification.

The verification policy (mode, challenge age, face matching) always comes from your Dashboard settings. The SDK cannot change it. For a different policy on some pages, create the session on your server with the override and send the user to the returned verifyUrl.

New-tab mode​

In new-tab mode your page stays open, and the SDK calls your callbacks:

const sdk = new SafePassage({
apiKey: 'pk_your_publishable_key',
returnUrl: location.origin + location.pathname,
mode: 'new-tab',
onComplete: async (result) => {
// Only called for a successful verification. Still confirm it on your server.
const response = await fetch('/api/verification/confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId: result.sessionId }),
});
if ((await response.json()).verified) showContent();
},
onCancel: () => {
showMessage('Verification was closed before it finished. You can start again.');
return false; // stay on this page
},
onError: (error) => {
showMessage(/popup/i.test(error.message)
? 'Please allow popups for this site, then try again.'
: 'Verification did not complete. You can try again.');
},
});

button.onclick = () => sdk.verify({ externalUserId: currentUserId }).catch(() => {
// onError has already been called with the same error.
});

onComplete receives { sessionId, status: 'verified', timestamp, externalUserId }.

Handling problems​

What happensHow the SDK reports itWhat to show
The SDK script did not load (blocked, offline)SafePassage is undefined"Verification is unavailable right now."
Invalid configuration (missing key, secret key, non-HTTPS returnUrl)new SafePassage() throwsFix the code; users cannot fix this.
Session could not be created (network, domain not allowed, key problem)verify() rejects, and onError is called"We could not start verification. Please try again."
Account limit (sandbox allowance used, no subscription, plan limit)The user is shown a SafePassage screen that explains the block. For a subscription or plan limit, verify() also rejects.Nothing extra. The account owner must act; see Troubleshooting.
More than 5 verify() calls in a minute from one pageverify() rejects with "Too many verification attempts. Please wait before trying again."; onError is called"Too many attempts. Please wait a minute and try again."
Popup blocked (new-tab mode)onError with "Failed to open verification window. Please check popup blocker settings."Ask the user to allow popups, or use redirect mode.
User closes the new-tab windowonCancel, then the opener goes to cancelUrl unless you return falseOffer to start again.
The session ends in an unrecoverable error (new-tab mode, rare)onError with "Verification failed: failed"Offer to start again.

A user who does not pass verification is not returned to your site with a failure status. They can try again on the hosted page or leave; if they leave with Return to site, they arrive at cancelUrl or returnUrl without parameters. Show the Verify my age button again in that case.

Return URL rules​

  • Production pages must use https://. http://localhost and http://127.0.0.1 (any port) work for local testing.
  • file:, javascript: and data: URLs are refused.
  • Existing query parameters are kept; sessionId, status and timestamp are added.
  • When Configuration → Domains is not empty, both the page using the SDK and the returnUrl must be on an allowed domain or one of its subdomains.

Environment​

The SDK always uses SafePassage's production service, which is correct for every customer integration, including your own staging and QA sites. Leave the environment option unset. Testing uses your account's sandbox allowance, not a separate environment.

Package details​

PropertyValue
npm package@safepassage/sdk
Current version3.5.6
TypeScriptType definitions included
BrowsersCurrent Chrome, Edge, Firefox and Safari, including mobile. Not Internet Explorer. Browser only; it does not run in Node.js.

SafePassage.VERSION returns the loaded version.