View as Markdown

Server recipes

All server calls use the secret key from an environment variable (here ERISED_SECRET_KEY), a short timeout, and never fail the user's action.

A small Node helper

// erised.js (server only). Node 18+.
const ERISED = 'https://app.erised.run';

export async function erised(path, body) {
  try {
    const res = await fetch(`${ERISED}/v1/${path}`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.ERISED_SECRET_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(3000),
    });
    if (!res.ok) console.warn('erised', path, res.status, await res.text());
  } catch (err) {
    console.warn('erised', path, err); // never fail the user's action
  }
}

export function identify({ user, anonymousId }) {
  return erised('identify', {
    userId: String(user.id),
    ...(anonymousId ? { anonymousId } : {}),
    properties: { email: user.email, traits: { plan: user.plan } },
  });
}

export function track({ userId, event, messageId, properties }) {
  return erised('track', { userId: String(userId), event, messageId, properties });
}

Next.js (App Router)

The snippet, in the root layout:

// app/layout.tsx
import Script from 'next/script';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script id="erised-init" strategy="afterInteractive">
          {`window.cdp = window.cdp || []; window.cdp.push(['init', '${process.env.NEXT_PUBLIC_ERISED_KEY}']);`}
        </Script>
        <Script src="https://app.erised.run/sdk/v0.js" strategy="afterInteractive" />
      </body>
    </html>
  );
}

Identify after login, in a server action or route handler:

// app/login/actions.ts
'use server';
import { cookies } from 'next/headers';
import { identify } from '@/lib/erised';

export async function login(formData: FormData) {
  const user = await signIn(formData); // your own auth
  const anonymousId = (await cookies()).get('erised_anonymous_id')?.value;
  await identify({ user, anonymousId: anonymousId ? decodeURIComponent(anonymousId) : undefined });
  // … redirect as usual
}

Reset at logout, in the client component that logs out:

window.cdp?.('reset');

Express

import cookieParser from 'cookie-parser';
import { identify, track } from './erised.js';

app.use(cookieParser());

app.post('/login', async (req, res) => {
  const user = await authenticate(req.body); // your own auth
  await identify({ user, anonymousId: req.cookies.erised_anonymous_id });
  res.redirect('/app');
});

app.post('/webhooks/payments', async (req, res) => {
  const order = await recordPayment(req.body); // your own logic
  await track({
    userId: order.userId,
    event: 'order_paid',
    messageId: `order_paid:${order.id}`,
    properties: { amount: order.total, currency: order.currency },
  });
  res.sendStatus(200);
});

When the API is on another host

The erised_anonymous_id cookie is host-only. If your API is on api.example.com and your site on example.com, read the cookie in the browser and send it with the login request:

const match = document.cookie.match(/(?:^|; )erised_anonymous_id=([^;]*)/);
const anonymousId = match ? decodeURIComponent(match[1]) : undefined;
await fetch('https://api.example.com/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email, password, anonymousId }),
});