Node.js SDK
Feature flags and "In your code" experiments on your server, decided the same way the browser decides them, and events sent from it. It runs on Node.js 18+, Next.js, Vercel and Cloudflare's edge runtimes, Deno and Bun, with no dependencies.
Install
npm install https://peekbird.com/sdk/peekbird-node.tgzThen make one client when your server starts, with a key from Site settings → Server keys:
import { Peekbird } from '@peekbird/node';
// Once, when your server starts. The key is in Site settings → Server keys.
const peekbird = new Peekbird({ key: process.env.PEEKBIRD_KEY });
await peekbird.ready();ready() waits for the first download of your flags and experiments; until then, flags are off and experiments answer null. After that the client decides locally, checks for changes every 30 seconds, and sends events every 5.
Decide
// In a request handler (Express, Next.js, Fastify, …): reads and sets Peekbird's cookies.
const visitor = peekbird.visitor(req, res);
if (peekbird.variation('one-page-checkout', visitor) === 'one-page') {
// Show the new version.
}const visitor = peekbird.visitor(req, res);
if (peekbird.flag('new-search', visitor)) {
// The new feature.
}variation(key, visitor)answers the variation's key, ornullwhen the visitor isn't in the test. It counts them in the test the first time: ask where the variations start to differ.flag(key, visitor)answerstrueorfalse;flags(visitor)answers every flag at once. Each answer is noted once per visitor, for the Feature flag filter.
Send events
peekbird.track(visitor, 'purchase', { revenue: 49.9, currency: 'USD', orderId: 'ORDER-123' });identify(visitor, { id, email, name }) says who the visitor is. Properties other than revenue, value, currency and orderId must be text, numbers or true/false.
The visitor
peekbird.visitor(...) takes any of these:
- A Node.js request and its response (Express, Fastify's
request.rawandreply.raw, Next.js API routes). Peekbird's cookies are set on the response for you. - A web
Request(Next.js middleware and route handlers, Cloudflare Workers, Deno, Bun). Addvisitor.cookiesToSetto your response. - Facts you give, for a visitor you know:
const visitor = peekbird.visitor({
id: user.id, // your own ID for someone signed in: the same answer on every device
attributes: { plan: user.plan, lifetimeValue: user.ltv },
country: 'US',
regionCode: 'TX',
timeZone: 'America/Chicago',
});From a request it reads the cookies, User-Agent, Accept-Language, Referer, the page's address, and behind Cloudflare CF-IPCountry and CF-Region-Code. What else a server knows, and what it can't, is on Server-side SDKs.
Express
import express from 'express';
import { peekbird } from './peekbird.js';
const app = express();
app.get('/checkout', (req, res) => {
const visitor = peekbird.visitor(req, res);
if (peekbird.variation('one-page-checkout', visitor) === 'one-page') {
return res.render('checkout-one-page');
}
res.render('checkout');
});Next.js
// middleware.ts: a split-URL test with no flicker, decided before the page renders.
import { NextResponse, type NextFetchEvent, type NextRequest } from 'next/server';
import { peekbird } from './lib/peekbird';
export function middleware(request: NextRequest, event: NextFetchEvent) {
const visitor = peekbird.visitor(request);
const response =
peekbird.variation('pricing-page', visitor) === 'new'
? NextResponse.rewrite(new URL('/pricing-new', request.url))
: NextResponse.next();
for (const cookie of visitor.cookiesToSet) response.headers.append('set-cookie', cookie);
// The edge can stop once it answers: send the exposure first.
event.waitUntil(peekbird.flush());
return response;
}
export const config = { matcher: '/pricing' };A rewrite in middleware gives the visitor the variation's page straight away. Server components can't set cookies, so let middleware give new visitors their ID:
// app/page.tsx: a server component reads the request's cookies and headers.
import { cookies, headers } from 'next/headers';
import { peekbird } from '@/lib/peekbird';
export default async function Page() {
const jar = await cookies();
const visitor = peekbird.visitor({
cookies: Object.fromEntries(jar.getAll().map((cookie) => [cookie.name, cookie.value])),
userAgent: (await headers()).get('user-agent') ?? undefined,
});
return peekbird.flag('new-search', visitor) ? <NewSearch /> : <Search />;
}Cloudflare Workers and serverless functions
import { Peekbird } from '@peekbird/node';
let peekbird;
export default {
async fetch(request, env, ctx) {
peekbird ??= new Peekbird({ key: env.PEEKBIRD_KEY });
await peekbird.ready();
const visitor = peekbird.visitor(request);
const page = peekbird.flag('new-search', visitor) ? await newSearch(request) : await search(request);
const response = new Response(page, { headers: { 'content-type': 'text/html' } });
for (const cookie of visitor.cookiesToSet) response.headers.append('set-cookie', cookie);
ctx.waitUntil(peekbird.flush());
return response;
},
};A function can be frozen once it answers, so send what's waiting first: ctx.waitUntil(peekbird.flush()) on Workers, await peekbird.flush() on Vercel, Netlify and AWS Lambda.
Consent
Where your site waits for consent (see Consent), the SDK follows the same rule as the snippet. For a visitor who hasn't agreed, it sets no cookies and sends no events, and experiments answer null. Flags are still answered, since deciding one stores and sends nothing. Tell it what your own banner knows with consent: true.
Options
new Peekbird({
key: process.env.PEEKBIRD_KEY,
refreshInterval: 30_000, // ms between checks for changed flags and experiments; 0: load once
flushInterval: 5_000, // ms between sends of waiting events
timeout: 5_000, // ms a request to Peekbird may take
onError: (error) => logger.warn(error), // a revoked key, Peekbird out of reach: never thrown
});close() stops checking for changes and sends what's waiting. Nothing the SDK does throws into your code.
