Authentication

The two credentials of the Identify API, who holds each, how to send them, and how to refresh tokens.

After this page you will be able to authenticate every call to the Identify API and keep tokens fresh.

Prerequisites: an app in Nortly, the Production Nortly API host (https://id.nortly.app) and Node.js 20 or later for the examples (TypeScript; drop the types for plain JavaScript).

The Identify API uses two different bearer credentials. Both are sent the same way, as Authorization: Bearer <value> (the word Bearer is case-sensitive), but they are held by different parties and unlock different endpoints.

API keyCustomer token
What it isAPI keyShort-lived token issued by POST /identify
Held byYour backend onlyThe merchant's browser
AllowsPOST /identify onlyGET /app and GET /customer only
ScopeOne app; can push data for any of its merchantsOne app and one merchant; read-only
LifetimeUntil it is revoked24 hours
Used onPOST /identifyGET /app, GET /customer
HostNortly APINortly API

1. The API key (backend)

Create an API key for your app in Nortly. The key:

  • is bound to exactly one app, so everything you push with it is attributed to that app;
  • allows POST /identify and nothing else; there is no separate permission to configure;
  • is shown only once, when you create it, so store it right away (API keys start with nk_);
  • stops working on the next request after it is revoked;
  • must stay on your server. Do not embed it in a browser, mobile app or public repository, and rotate it if it leaks.

Send it to the Nortly API host as Authorization: Bearer <api key>: the word Bearer, exactly one space, then the key.

const res = await fetch("https://id.nortly.app/api/2026-07/identify", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.NORTLY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ shopId: "1234567890" }),
});

We recommend reading the key from an environment variable or a secret store, never from source code.

A request without a valid key is answered with 401 unauthorized. Revoked keys are rejected the same way, immediately.

StatuserrorCause
401unauthorizedThe Authorization header is missing or is not Bearer <api key>, or the key is malformed, unknown or revoked. Check the key and that you call the Nortly API host.

2. The customer token (browser)

POST /identify returns the token:

{
  "token": "EXAMPLE-NOT-A-REAL-TOKEN",
  "expiresAt": "2026-07-16T09:30:00.000Z"
}
  • Treat token as an opaque string. Do not parse it or depend on its contents.
  • It is bound to the app of your API key and to the shopId you sent, so it can only read that one merchant's data.
  • It is valid for 24 hours; expiresAt is the exact expiry in UTC.
  • It is safe to use in the browser. Pass it to your frontend and send it to GET /app and GET /customer:
const res = await fetch("https://id.nortly.app/api/2026-07/customer", {
  headers: { Authorization: `Bearer ${customerToken}` },
});

A token is answered with 401 unauthorized when it is missing, malformed, expired, or revoked by Nortly (revocation is enforced on GET /customer).

Token lifetime and refresh

There is no refresh endpoint and no refresh token. To get a new token, call POST /identify again for the same shopId:

  1. Keep expiresAt next to the token in your backend or frontend state.
  2. Renew shortly before it, for example when less than an hour remains, or when a read endpoint answers 401.
  3. Repeating POST /identify is safe: send the same body, or just { "shopId": "1234567890" }, since only shopId is required. Each call issues a new 24-hour token; tokens issued earlier remain valid until they expire or are revoked.

We recommend refreshing early, so the browser never sees an expired token:

const REFRESH_MARGIN_MS = 60 * 60 * 1000; // renew when less than an hour is left

function needsRefresh(expiresAt: string): boolean {
  return Date.parse(expiresAt) - Date.now() < REFRESH_MARGIN_MS;
}

A typical pattern is a small endpoint on your backend that your frontend calls whenever it needs a token; it calls POST /identify when the cached token needs a refresh and returns token and expiresAt. The example at the end of this page is such an endpoint.

Rate limiting

Rate limiting in front of the service can answer 429 on any route. It is not tied to either credential. Back off and retry: wait, then repeat the call with a growing delay (for example 0.5 s, 1 s, 2 s).

Next steps

Example

A complete token endpoint for your backend (Node.js 20 or later). Your frontend calls GET /nortly-token; the server keeps the API key, calls POST /identify when needed, caches the token per shop and renews it before expiresAt. Save it as token-endpoint.ts and run it with NORTLY_API_KEY=<your API key> npx tsx token-endpoint.ts.

The shop id must come from your own authenticated session, never from a value the browser can choose. The shopIdFromSession function below is a stand-in for that lookup: replace it before real use.

import { createServer, type IncomingMessage } from "node:http";

const IDENTIFY_URL = "https://id.nortly.app/api/2026-07/identify";
const API_KEY = process.env.NORTLY_API_KEY;
const PORT = Number(process.env.PORT ?? 3000);
const REFRESH_MARGIN_MS = 60 * 60 * 1000; // renew when less than an hour is left

if (!API_KEY) {
  console.error("Set NORTLY_API_KEY to your API key.");
  process.exit(1);
}

type CustomerToken = { token: string; expiresAt: string };

const cache = new Map<string, CustomerToken>();
const inFlight = new Map<string, Promise<CustomerToken>>();

class IdentifyError extends Error {
  status: number;
  constructor(status: number, code?: string) {
    super(`POST /identify answered ${status}${code ? ` ${code}` : ""}`);
    this.status = status;
  }
}

async function requestToken(shopId: string): Promise<CustomerToken> {
  const res = await fetch(IDENTIFY_URL, {
    method: "POST",
    headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ shopId }),
  });
  if (!res.ok) {
    const body = (await res.json().catch(() => ({}))) as { error?: string };
    // 401: missing, malformed, unknown or revoked key. 429 and 503: retry later.
    throw new IdentifyError(res.status, body.error);
  }
  return (await res.json()) as CustomerToken;
}

// One identify call per shop at a time, even when many requests arrive together.
function getToken(shopId: string): Promise<CustomerToken> {
  const cached = cache.get(shopId);
  if (cached && Date.parse(cached.expiresAt) - Date.now() > REFRESH_MARGIN_MS) {
    return Promise.resolve(cached);
  }
  let pending = inFlight.get(shopId);
  if (!pending) {
    pending = requestToken(shopId)
      .then((fresh) => {
        cache.set(shopId, fresh);
        return fresh;
      })
      .finally(() => inFlight.delete(shopId));
    inFlight.set(shopId, pending);
  }
  return pending;
}

// Replace with your real session lookup (cookie, session store, signed-in user).
function shopIdFromSession(req: IncomingMessage): string | null {
  const header = req.headers["x-demo-shop-id"];
  return typeof header === "string" && header ? header : null;
}

createServer(async (req, res) => {
  const send = (status: number, body: unknown) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(body));
  };
  if (req.method !== "GET" || req.url !== "/nortly-token") return send(404, { error: "not_found" });

  const shopId = shopIdFromSession(req);
  if (!shopId) return send(401, { error: "unauthorized" });

  try {
    send(200, await getToken(shopId)); // { token, expiresAt }
  } catch (err) {
    console.error(err);
    // Do not pass Nortly errors on to the browser: it can only retry later.
    const retryable = err instanceof IdentifyError && (err.status === 429 || err.status === 503);
    send(retryable ? 503 : 502, { error: "token_unavailable" });
  }
}).listen(PORT, () => console.log(`Token endpoint on http://localhost:${PORT}/nortly-token`));

To try it, call GET http://localhost:3000/nortly-token with the header x-demo-shop-id: 1234567890 from any HTTP client. It answers {"token":"...","expiresAt":"..."}.


Did this page help you?