Test the 4 public operations below. Replace the host and the server key with your own values.
The server check
Request
curl -sS https://konto.example.no/api/v1/access \
-H "Authorization: Bearer $SERVER_KEY" \
-H "Content-Type: application/json" \
-d '{"article": "budget-plan", "level": "paid"}'
Response 200
{
"access": "paywall",
"freeLeft": null,
"known": false,
"setMeter": null,
"clearReader": false,
"tierWall": null
}
The hand-off exchange
Request
curl -sS https://konto.example.no/api/v1/handoff \
-H "Authorization: Bearer $SERVER_KEY" \
-H "Content-Type: application/json" \
-d '{"code": "5qyV3m0lLzVn0nIyl2m0pQm0r9m9Qn2o1iP7c5b3d1A"}'
Response 200
{
"reader": "ns_rt_1_...",
"maxAge": 2591000
}
The view of the publication
The browser sends this request for the embed.
Request
curl -sS "https://konto.example.no/api/v1/embed/site?locale=en" \
-H "Origin: https://www.example.no"
The entitlement read
Part 17 gives the rules. Send the value of the reader cookie or the reader ID.
Request
curl -sS https://konto.example.no/api/v1/entitlements \
-H "Authorization: Bearer $SERVER_KEY" \
-H "Content-Type: application/json" \
-d '{"reader": "ns_rt_1_..."}'
Response 200
{
"known": true,
"readerId": "0193f0b2-1111-7a4e-9d2b-3f6a8c1e2d4f",
"subscription": {
"id": "0193f0b2-2222-7a4e-9d2b-3f6a8c1e2d4f",
"status": "active",
"plan": {
"id": "0193f0b2-3333-7a4e-9d2b-3f6a8c1e2d4f",
"name": "Monthly A1"
},
"currentPeriodEnd": "2027-02-10T09:00:00Z",
"cancelAtPeriodEnd": false,
"endsAt": null
},
"accessKeys": ["paid"]
}
A webhook event for tests
Norspire sends webhook events to your receiver, so you do not call it. Use the request below to test your receiver. The signature in this example is a placeholder, so your receiver refuses it. Part 16 gives the check.
Request
curl -sS -i https://www.example.no/norspire/webhooks \
-H "Content-Type: application/json" \
-H "webhook-id: 0193f0b2-5c1e-7a4e-9d2b-3f6a8c1e2d4f" \
-H "webhook-timestamp: 1768039200" \
-H "webhook-signature: v1,<base64 signature>" \
-d '{"id":"0193f0b2-5c1e-7a4e-9d2b-3f6a8c1e2d4f","type":"subscription.created","timestamp":"2027-01-10T09:00:00Z","data":{"sequence":1,"host":"konto.example.no","reader":{"id":"0193f0b2-1111-7a4e-9d2b-3f6a8c1e2d4f","email":"reader@example.no"},"subscription":{"id":"0193f0b2-2222-7a4e-9d2b-3f6a8c1e2d4f","status":"active","plan":{"id":"0193f0b2-3333-7a4e-9d2b-3f6a8c1e2d4f","name":"Monthly A1"},"accessKeys":["paid"],"currentPeriodEnd":"2027-02-10T09:00:00Z","cancelAtPeriodEnd":false,"endsAt":null,"endReason":null,"paymentMethod":"card","currency":"NOK"},"charge":null,"refund":null}}'
Response 400
HTTP/1.1 400 Bad Request
A problem answer
This request sends a wrong server key.
Request
curl -sS -i https://konto.example.no/api/v1/access \
-H "Authorization: Bearer ns_sk_test_wrong" \
-H "Content-Type: application/json" \
-d '{"article": "budget-plan", "level": "paid"}'
Response 401
HTTP/1.1 401 Unauthorized
Content-Type: application/problem+json
WWW-Authenticate: Bearer
{
"type": "urn:norspire:problem:unauthenticated",
"title": "The request has no valid credential.",
"status": 401,
"code": "unauthenticated",
"requestId": "a3f1c9d2"
}
The runnable example
The file docs/examples/minimal-site.mjs is a site with 1 paid article. It is plain Node.js with no package. It follows each rule of this guide. Start it with your values:
SUBSCRIPTION_ORIGIN=https://konto.example.no SERVER_KEY=ns_sk_test_... node docs/examples/minimal-site.mjs
The file in full:
// A publisher site with 1 paid article and the paywall of Norspire. Plain Node.js, no package.
//
// SUBSCRIPTION_ORIGIN=http://a1.localhost:3000 SERVER_KEY=ns_sk_test_... node minimal-site.mjs
//
// List the origin of this site, for example http://127.0.0.1:4200, as a site origin on the
// Integration page. On an https site, name the cookies __Host-ns_reader and __Host-ns_meter and
// add Secure to them.
import { createServer } from 'node:http';
const BUDGET_MS = 1000;
const WINDOW_MS = 10_000;
const MIN_RESULTS = 20;
const MIN_OPEN_SECONDS = 1;
const MAX_OPEN_SECONDS = 30;
const DEFAULT_OPEN_SECONDS = 5;
const ARTICLE = 'example-paid';
// The labels of the legal links. Copy the 2 values from the Integration page.
const LABELS = { cancel: 'Cancel your agreement here', withdraw: 'Withdraw from your agreement' };
/**
* The circuit breaker for the server check. It keeps the results of the last 10 seconds. With 20
* results or more, it opens at 50 percent failures or more. With fewer, it opens after 5 failures
* in a row. It stays open for the Retry-After of the last failed answer, from 1 to 30 seconds, or
* else 5 seconds. Then it lets 1 call through.
*/
export function createBreaker({ now = Date.now } = {}) {
let results = [];
let openUntil = 0;
let probing = false;
const open = (retryAfter) => {
const seconds = Number.isFinite(retryAfter) ? retryAfter : DEFAULT_OPEN_SECONDS;
const bounded = Math.min(Math.max(seconds, MIN_OPEN_SECONDS), MAX_OPEN_SECONDS);
openUntil = now() + bounded * 1000;
probing = false;
};
return {
/** `true` while the breaker is open. The hand-off exchange asks this and counts nothing. */
isOpen: () => now() < openUntil,
/** `true` when the server check may run. After the open time, it lets 1 call through. */
allow() {
if (now() < openUntil) return false;
if (openUntil === 0) return true;
if (probing) return false;
probing = true;
return true;
},
/** Records the result of 1 server check. `failed` is a timeout, an error, a 429 or a 5xx. */
record(failed, retryAfter) {
const time = now();
if (probing) {
probing = false;
results = [];
if (failed) open(retryAfter);
else openUntil = 0;
return;
}
results = results.filter((result) => time - result.time < WINDOW_MS);
results.push({ time, failed });
const failures = results.filter((result) => result.failed).length;
const inARow = results.findLastIndex((result) => !result.failed);
const trailing = results.length - 1 - inARow;
const tripped =
results.length >= MIN_RESULTS ? failures * 2 >= results.length : trailing >= 5;
if (failed && tripped) open(retryAfter);
},
};
}
const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (c) => `&#${c.codePointAt(0)};`);
const escapeJson = (text) =>
text.replace(
/[<>&\p{Zl}\p{Zp}]/gu,
(c) => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`,
);
const PAYWALLED = [
'MARKER-EXAMPLE-PAID. The numbers in the budget add up only when the three smaller posts stay as they are.',
'This part is the paid part of the article. The server sends it only when Norspire answers full.',
];
const TEASER = [
'The council passed the budget for next year on Tuesday evening. It has one line about substitute teachers.',
];
export function startSite({ origin, key, port, fetchImpl = fetch, now = Date.now }) {
const breaker = createBreaker({ now });
const call = (path, body) =>
fetchImpl(`${origin}${path}`, {
method: 'POST',
headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(BUDGET_MS),
});
/** The server check. It returns the answer, or `null` for no answer. */
async function check(cookies) {
if (!breaker.allow()) return null;
try {
const body = { article: ARTICLE, level: 'paid' };
if (cookies.ns_reader) body.reader = cookies.ns_reader;
if (cookies.ns_meter) body.meter = cookies.ns_meter;
const response = await call('/api/v1/access', body);
const header = response.headers.get('retry-after');
const retryAfter = header === null ? undefined : Number(header);
// A wait does not repair a 400, a 401 or a 413, so they are not failures of the breaker.
const failed = response.status === 429 || response.status >= 500;
if (response.status !== 200) {
breaker.record(failed, retryAfter);
const problem = await response.json().catch(() => ({}));
console.error(`Server check ${response.status} ${problem.code} ${problem.requestId}`);
return null;
}
const answer = await response.json();
const valid = ['full', 'registration_wall', 'paywall'].includes(answer.access);
breaker.record(!valid);
return valid ? answer : null;
} catch (error) {
breaker.record(true);
console.error(`Server check failed: ${error.name}`);
return null;
}
}
/** The hand-off exchange. It returns the cookie header lines, or no line for each failure. */
async function exchange(code) {
if (breaker.isOpen()) return [];
try {
const response = await call('/api/v1/handoff', { code });
if (response.status !== 200) return [];
const { reader, maxAge } = await response.json();
return [cookie('ns_reader', reader, maxAge)];
} catch {
return [];
}
}
const cookie = (name, value, maxAge) =>
`${name}=${value}; Max-Age=${maxAge}; Path=/; HttpOnly; SameSite=Lax`;
/** Step 1 of each request: take ns_handoff out of the address, on each path. */
function splitHandoff(search) {
const kept = [];
const codes = [];
for (const pair of search.replace(/^\?/, '').split('&').filter(Boolean)) {
const [name, ...rest] = pair.split('=');
let decoded = name;
let value = rest.join('=');
try {
decoded = decodeURIComponent(name.replace(/\+/g, ' '));
value = decodeURIComponent(value.replace(/\+/g, ' '));
} catch {}
if (decoded === 'ns_handoff') codes.push(value);
else kept.push(pair);
}
return { codes, query: kept.length === 0 ? '' : `?${kept.join('&')}` };
}
const server = createServer(async (request, response) => {
const url = new URL(request.url, `http://${request.headers.host}`);
const { codes, query } = splitHandoff(url.search);
const reads = request.method === 'GET' || request.method === 'HEAD';
if (reads && codes.length > 0) {
// The last value is the real code. A HEAD request calls no exchange.
const lines = request.method === 'GET' ? await exchange(codes.at(-1)) : [];
if (lines.length > 0) response.setHeader('Set-Cookie', lines);
response.writeHead(303, { Location: `${url.pathname}${query}`, 'Cache-Control': 'no-store' });
response.end();
return;
}
if (url.pathname !== `/articles/${ARTICLE}`) {
response.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
response.end('Not found');
return;
}
const headers = {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'private, no-store',
};
if (request.method === 'HEAD') {
response.writeHead(200, headers);
response.end();
return;
}
const cookies = Object.fromEntries(
(request.headers.cookie ?? '').split(/;\s*/).map((pair) => pair.split(/=(.*)/s).slice(0, 2)),
);
const answer = await check(cookies);
const setCookie = [];
if (answer?.clearReader) setCookie.push(cookie('ns_reader', '', 0));
if (answer?.setMeter) setCookie.push(cookie('ns_meter', answer.setMeter, 31 * 24 * 60 * 60));
if (setCookie.length > 0) headers['Set-Cookie'] = setCookie;
response.writeHead(200, headers);
response.end(page(answer, `http://${request.headers.host}${url.pathname}${query}`));
});
function page(answer, pageUrl) {
const known = answer?.known ? ' known' : '';
const wallType = answer === null ? 'unavailable' : answer.access;
const subscribe = `${origin}/subscribe?return=${encodeURIComponent(pageUrl)}`;
const full = answer?.access === 'full';
const paragraphs = (list) => list.map((text) => `<p>${escapeHtml(text)}</p>`).join('');
const jsonLd = escapeJson(
JSON.stringify({
'@context': 'https://schema.org',
'@type': 'NewsArticle',
headline: 'The budget and the substitute teachers',
datePublished: '2026-11-20',
author: { '@type': 'Person', name: 'Example Reporter' },
isAccessibleForFree: false,
hasPart: {
'@type': 'WebPageElement',
isAccessibleForFree: false,
cssSelector: '.paywalled-content',
},
}),
);
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The budget and the substitute teachers</title>
<script type="application/ld+json">${jsonLd}</script>
<script type="module" src="${escapeHtml(origin)}/embed/v1/embed.js" data-locale="en"></script>
</head>
<body>
<header>
<norspire-account${known}><a href="${escapeHtml(origin)}/login?return=${encodeURIComponent(pageUrl)}">Log in</a></norspire-account>
</header>
<main>
<article>
<h1>The budget and the substitute teachers</h1>
${typeof answer?.freeLeft === 'number' ? `<norspire-meter free-left="${answer.freeLeft}"${known}><p>You have ${answer.freeLeft} free articles left this month.</p></norspire-meter>` : ''}
${paragraphs(TEASER)}
${
full
? `<div class="paywalled-content">${paragraphs(PAYWALLED)}</div>`
: `<norspire-wall type="${wallType}" article="${ARTICLE}"${known}><p><a href="${escapeHtml(subscribe)}">Subscribe to read on</a></p></norspire-wall>`
}
</article>
</main>
<footer>
<h2>Your agreement</h2>
<norspire-legal-links><a href="${escapeHtml(origin)}/cancel">${escapeHtml(LABELS.cancel)}</a> <a href="${escapeHtml(origin)}/withdraw">${escapeHtml(LABELS.withdraw)}</a></norspire-legal-links>
</footer>
</body>
</html>`;
}
return new Promise((resolve) => {
server.listen(port, '127.0.0.1', () => resolve(server));
});
}
if (import.meta.main) {
const origin = process.env.SUBSCRIPTION_ORIGIN;
const key = process.env.SERVER_KEY;
const port = Number(process.env.PORT ?? '4200');
if (!origin || !key) {
console.error('Set SUBSCRIPTION_ORIGIN and SERVER_KEY.');
process.exit(1);
}
await startSite({ origin, key, port });
console.log(`Open http://127.0.0.1:${port}/articles/${ARTICLE}`);
}