# Connect your Node backend Use the Node adapter with an existing Node.js 22+ HTTP application. It owns the temporary sign-in attempt, callback verification, encrypted cookies, cancellation and sign-out. You do not need a customer or session database. The browser opens Mementom in a separate authorization window using the shared browser controller. Your server receives the one-use callback, verifies it and sends the window's public request ID and completion status to its opener. The original application then refreshes its server status. ## Install and configure Use `@mementom/sdk/node` from the SDK package, or download [the Node adapter](/developers/downloads/mementom-node.mjs), [the server SDK](/developers/downloads/mementom-sdk.mjs), [the browser controller](/developers/downloads/mementom-browser.mjs) and [the backend example](/developers/downloads/node-backend.mjs). Keep the three modules in one server-only directory outside your web root. The adapter serves only the existing browser controller at `/mementom/browser.mjs`. In your app's Integration settings, select your fixed HTTPS app origin and set the Login challenge's exact return URI to `https://your-app.example/mementom/return`. Register your server's public response key. Keep the matching private key and company server credential in your server secret store. ```js import {createMementomNodeAdapter} from '@mementom/sdk/node'; // Downloaded modules: import from './mementom-node.mjs' instead. const mementom = await createMementomNodeAdapter({ appOrigin: 'https://your-app.example', applicationId: process.env.MEMENTOM_APPLICATION_ID, credential: process.env.MEMENTOM_SERVER_CREDENTIAL, privateKey: serverPrivateKey, cookieKey: Buffer.from(process.env.MEMENTOM_COOKIE_KEY, 'base64url'), }); // Inside your existing node:http server handler, before ordinary app routes: if (await mementom.handle(request, response)) return; ``` `cookieKey` must be 32 cryptographically random bytes, persisted in your secret store. Keep it stable across restarts and identical across instances. Rotating it ends local browser sessions and pending attempts. HTTPS cookies are HttpOnly, Secure, SameSite=Lax, scoped to the host and bound cryptographically to this app, origin and route prefix. HTTP is accepted only for loopback development. The default Mementom authorization origin is `https://auth.mementom.app`. Private installations can explicitly set `authorizationOrigin` and `apiBaseUrl`; never derive either, or `appOrigin`, from incoming Host or forwarded headers. Configure the reverse proxy to preserve same-origin request headers and authorization-window openers. Do not apply an app-wide opener policy that severs this flow. Avoid logging callback URLs, query strings, cookies, response bodies or provider errors in your application, proxy and tracing systems. ## Add the session QR badge Follow the [retailer badge guide](session-badge.md) to install the shared component and place it on a button. The adapter owns the same-origin `POST /mementom/badge/start`, `/mementom/badge/status` and `/mementom/badge/cancel` handlers. The badge sends its public request ID. The backend keeps the relay watcher private and verifies the result before establishing the session. Once connected, the badge opens the hosted Mementom Activity window and reads the visit's receipts through the adapter's `/mementom/activity` route. You can use the standalone button below for other authorization actions. ## Open the authorization window Import the browser controller served by the adapter in your existing application. Call `open()` directly in the click handler, before awaiting anything: ```js import {createAuthorizationWindow} from '/mementom/browser.mjs'; const secure = createAuthorizationWindow({returnOrigin: location.origin}); let pendingRequestId; async function post(path, input, signal) { const response = await fetch('/mementom/' + path, { method: 'POST', credentials: 'same-origin', signal, headers: {'Content-Type': 'application/json'}, body: JSON.stringify(input), }); if (!response.ok) throw new Error('Please try again.'); return response.json(); } signInButton.onclick = () => { secure.open(({requestId, signal}) => { pendingRequestId = requestId; return post('start', {requestId}, signal); }).then(async result => { if (result.status !== 'complete') { await post('cancel', {requestId: pendingRequestId}).catch(() => {}); } await refreshStatus(); }).catch(() => showSignInRetry()); }; async function refreshStatus() { const response = await fetch('/mementom/status', { credentials: 'same-origin', cache: 'no-store', }); if (!response.ok) throw new Error('Please try again.'); const {connected} = await response.json(); updateYourExistingApp(connected); } cancelButton.onclick = () => { post('cancel', {requestId: pendingRequestId}).finally(() => secure.cancel()); }; signOutButton.onclick = () => { secure.open(({requestId, signal}) => post('logout', {requestId}, signal)) .then(refreshStatus, refreshStatus); }; ``` Use your own existing buttons, loading state and retry message. If you use a private authorization service, pass the same `authorizationOrigin` to the browser controller. Closing or timing out the window should cancel its pending server attempt. A popup completion message never grants application access; use `/mementom/status` and the service-checked server operation. The return window closes and focuses its opener. If the browser prevents closing, it retains its ended screen. It never becomes your application or its activity window. Keep the original app and activity window intact. ## Routes | Route | Method | Result | | --- | --- | --- | | `/mementom/start` | POST JSON `{requestId}` | Issued `authorizationUrl`; encrypted pending cookie. | | `/mementom/status` | GET | `{connected}` checked with Mementom each time. | | `/mementom/return` | GET | Bound callback exchange and standalone window completion. | | `/mementom/cancel` | POST JSON `{requestId}` | Atomically cancels this attempt; keeps an existing session. | | `/mementom/logout` | POST JSON `{requestId}` | Revokes the current session, clears local cookies and issues the service logout window. | | `/mementom/browser.mjs` | GET | Shared browser controller, with no server SDK or credentials. | Only same-origin POST requests with JSON are accepted. `requestId` is the public UUID generated by the browser controller; the server generates the separate private state and binds it to the issued service request and configuration. Callbacks reject duplicate or unknown parameters, wrong state, another browser, expired attempts, changed configuration and replay. A failed callback requires a fresh attempt. Concurrent completion and cancellation have one atomic winner. The default prefix can be changed with `prefix`. Register the matching return URI and update the browser route paths together. Browser responses contain no company session, relationship identity, insight values, private key or server credential. An authorization URL is intentionally passed only to the owned secure window. ## Use insights on your server ```js const permittedInsights = await mementom.readInsights(request); const permittedHistory = await mementom.insightHistory(request, { origin: 'https://your-app.example', }); await mementom.ingestInsights(request, { expectedRevision: catalog.revision, datasetId: yourDatasetId, eventId: persistedBusinessEvent.eventId, sample: { schemaVersion: 1, observedAt: persistedBusinessEvent.observedAt, values: persistedBusinessEvent.values, }, }); ``` These are server-only hooks using the current cookie session. Mementom checks its current sharing permissions for each call. Persist trusted business events before ingestion and reuse the same event ID, timestamp and values when retrying. Do not mount an endpoint that accepts browser assertions as a trusted business event. Project only the specific information your app needs from an authorized read. ## Protect a business operation Configure `onAction` when creating the adapter. In your own authenticated, same-origin business route, verify eligibility, resolve the immutable company operation and load the selected published challenge definition. Then call `startAction(request, response, options)` and return its `authorizationUrl` to the same shared browser controller: ```js // Adapter creation: const mementom = await createMementomNodeAdapter({ ...serverConfiguration, onAction: async ({operationId, context, decision, consumption}) => { // Persist and execute once by operationId in YOUR business database. // Recheck the exact order revision/terms and current business eligibility. await orders.approveOnce(operationId, context.orderId, context.revision); }, }); // Your trusted business handler, after authentication and CSRF checks: const result = await mementom.startAction(request, response, { requestId: validatedPublicWindowRequestId, challengeActionId: published.actionId, resourceDigest: persistedOperation.resourceDigest, definition: { version: published.version, returnUri: mementom.callbackUri, requestedRight: published.requestedRight, resourceSummary: published.resourceSummary, consequence: published.consequence, }, context: {orderId: persistedOperation.orderId, revision: persistedOperation.revision}, }); // Preserve the Set-Cookie header written by startAction, then send result as JSON. ``` The action must use this adapter's callback URI and an active managed action challenge. Include `networkPolicyId` and `networkPolicyVersion` in `definition` when that challenge uses a network policy. The adapter stores the server-held session, operation nonce, state, challenge, immutable resource and visible-details bindings. It verifies and consumes the service decision before calling `onAction`. Denied, bypassed, expired, changed or replayed requests never call the hook. A request needing fresh sign-in must restart sign-in before starting a new action. One-use decision consumption cannot form a transaction with your database. Implement durable, idempotent business execution using `operationId`; do not retry a callback or interpret “already consumed” as permission to run a business operation. If execution fails after consumption, reconcile your own operation record or request fresh authorization. Store only JSON-compatible, server-owned context. Existing SDK account-access methods remain available through your server's `Mementom.connect` handle; this adapter adds no account database. ## Storage and deployment The built-in memory store supports one Node process, expires attempts and limits pending entries to 10,000. Default attempt lifetime is 10 minutes, capped by the service expiry. Default network timeout is 15 seconds with redirects rejected. `timeoutMs` accepts 100–30,000 ms; `attemptTtlMs` accepts 1,000–1,800,000 ms. Restarting the process ends pending attempts; an encrypted session cookie can continue when the persistent cookie key and Mementom authorization remain valid. For several processes, replicas, or pending-attempt continuity across restarts, inject `attemptStore` with these asynchronous methods: ```js const attemptStore = { async put(id, record) { /* insert only if absent; TTL is record.expiresAt */ }, async get(id) { /* private JSON record, or null if absent/expired */ }, async take(id) { /* ATOMIC remove-and-return, or null; exactly one winner */ }, }; ``` `take` must be atomic across all instances. Use an atomic database statement, transaction or Redis operation, never a separate get followed by delete. Enforce expiry and capacity in the store, isolate this app's namespace, encrypt sensitive storage where appropriate, and share its credentials only among your backend instances. Records contain transient session and request bindings, so they must never be exposed in client storage, dashboards or logs. They are not a customer identity store. Use the default memory store for ordinary single-process use.