Skip to content

Node examples

Small programs built on the audience-kit package, one per thing a site or service does. Each exports the function it is built around, so the SDK’s tests run it against a stub API, and runs as a program when started directly:

Terminal window
npm install audience-kit
AUDIENCEKIT_TOKEN=akst_… AUDIENCEKIT_HOST=hotmess.social node --experimental-strip-types listings-site.ts
File What it shows
listings-site.ts A page of the audience’s public listings, read with a service token and cached for five minutes
news-digest.ts A Markdown digest of a locale’s news and its national news, for a newsletter job
facebook-sign-in.ts Signing people in with Facebook on a server, one session per browser
member-actions.ts What a signed-in member does: RSVP, calendar links, the door pass and reporting
community-export.ts The whole community as JSON, for a static site generator
listings-site.ts
// A page of the audience's public listings, as a venue guide or a city site would show them.
//
// AUDIENCEKIT_TOKEN=akst_… AUDIENCEKIT_HOST=hotmess.social node --experimental-strip-types listings-site.ts
//
// The service token needs the `public:read` scope. Listings change a few times a day, so the page is cached for five
// minutes rather than read on every request.
import { createServer } from "node:http";
import { AudienceKitClient, isPublicListing, type PublicListing } from "audience-kit";
const escape = (text: string | null | undefined): string =>
(text ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
/** One listing as HTML: venues with their address, events with their time, posts with their text. */
export function renderListing(listing: PublicListing, timeZone = "America/Denver"): string {
switch (listing.kind) {
case "venue":
return `<h2>${escape(listing.title)}</h2><p>${escape(listing.address)}</p>`;
case "event": {
const when = listing.start_at
? new Date(listing.start_at).toLocaleString("en-US", { timeZone, weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })
: "";
const canceled = listing.is_canceled ? " <strong>Canceled</strong>" : "";
return `<h3>${escape(listing.title)}</h3><p><time>${escape(when)}</time> at ${escape(listing.venue_name)}${canceled}</p>`;
}
case "post":
return `<article><h3>${escape(listing.title)}</h3><p>${escape(listing.description)}</p></article>`;
default:
return "";
}
}
/** The whole page. "Community" listings show in full only to members, so they're left out of a public page. */
export async function renderPage(client: AudienceKitClient): Promise<string> {
const listings = (await client.publicListings()).filter(isPublicListing);
return `<!doctype html><meta charset="utf-8"><title>What's on</title>\n${listings.map((listing) => renderListing(listing)).join("\n")}\n`;
}
/** Keeps the rendered page for `seconds`, so the API is asked at most once in that time. */
export function cached(render: () => Promise<string>, seconds = 300, now = () => Date.now()): () => Promise<string> {
let page: { html: string; until: number } | null = null;
return async () => {
if (page === null || now() >= page.until) page = { html: await render(), until: now() + seconds * 1000 };
return page.html;
};
}
if (import.meta.url === `file://${process.argv[1]}`) {
const client = AudienceKitClient.fromEnvironment();
const page = cached(() => renderPage(client));
createServer(async (_request, response) => {
try {
response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(await page());
} catch (error) {
console.error(error);
response.writeHead(502).end("The listings aren't available right now.");
}
}).listen(8080, () => console.log("http://localhost:8080"));
}
news-digest.ts
// A Markdown digest of a locale's news, for a newsletter or a Discord post.
//
// AUDIENCEKIT_TOKEN=<application API key> AUDIENCEKIT_HOST=hotmess.social node --experimental-strip-types news-digest.ts "Denver"
//
// Returns nothing for an audience without Soapbox, rather than failing.
import { AudienceKitClient, type Article } from "audience-kit";
function line(article: Article): string {
// A teaser carries only the start of the article: the rest is on the publication's site.
const link = article.teaser && article.canonicalUrl ? ` ([read on ${article.publication.name}](https://github.com/lwm-luminx/audience-kit-sdk/blob/main/node/examples/${article.canonicalUrl}))` : "";
const disclosure = article.disclosure ? `\n _${article.disclosure}_` : "";
return `- **${article.title}**, ${article.byline} for ${article.publication.name}${link}${article.summary ? `\n ${article.summary}` : ""}${disclosure}`;
}
/** The digest for the locale named `localeName` (or the audience's first): its news, then the national news. */
export async function digest(client: AudienceKitClient, localeName?: string): Promise<string> {
const locales = await client.locales();
const locale = locales.find((l) => l.name === localeName) ?? locales[0];
if (!locale) return "";
const [local, national] = await Promise.all([
client.articles({ localeId: locale.id, first: 10 }),
client.nationalArticles({ localeId: locale.id, first: 5 }),
]);
const sections = [`# ${locale.name} this week`];
if (local.length > 0) sections.push(`## Local news\n\n${local.map(line).join("\n")}`);
const seen = new Set(local.map((article) => article.id));
const elsewhere = national.filter((article) => !seen.has(article.id));
if (elsewhere.length > 0) sections.push(`## Around the country\n\n${elsewhere.map(line).join("\n")}`);
return sections.length > 1 ? `${sections.join("\n\n")}\n` : "";
}
if (import.meta.url === `file://${process.argv[1]}`) {
console.log(await digest(AudienceKitClient.fromEnvironment(), process.argv[2]));
}
facebook-sign-in.ts
// Signing people in with Facebook on a server: each browser gets its own AudienceKit session, kept server-side.
//
// FACEBOOK_APP_ID=… AUDIENCEKIT_HOST=hotmess.social node --experimental-strip-types facebook-sign-in.ts
//
// The API trades Facebook's code with the app secret, so the secret never reaches this server. Keep sessions in your
// database or framework's session store in production; the Map here is for the example.
import { randomBytes, timingSafeEqual } from "node:crypto";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { AudienceKitClient, AudienceKitError, type TokenStore } from "audience-kit";
/** One browser's session: its AudienceKit token and audience, and the OAuth state of a sign-in in progress. */
interface BrowserSession {
token: string | null;
audienceId: string | null;
state: string | null;
}
/** A `TokenStore` over one browser's session, so the client reads and writes that browser's token only. */
export class BrowserTokenStore implements TokenStore {
constructor(private readonly session: BrowserSession) {}
loadToken() {
return this.session.token;
}
saveToken(token: string) {
this.session.token = token;
}
deleteToken() {
this.session.token = null;
this.session.audienceId = null;
}
loadAudienceId() {
return this.session.audienceId;
}
saveAudienceId(audienceId: string | null) {
this.session.audienceId = audienceId;
}
}
const sessions = new Map<string, BrowserSession>();
/** The browser's session, made on its first request and named by an HttpOnly cookie. */
export function sessionFor(request: IncomingMessage, response: ServerResponse): BrowserSession {
const id = /(?:^|;\s*)sid=([a-f0-9]{32})/.exec(request.headers.cookie ?? "")?.[1];
const found = id ? sessions.get(id) : undefined;
if (found) return found;
const fresh = randomBytes(16).toString("hex");
const session: BrowserSession = { token: null, audienceId: null, state: null };
sessions.set(fresh, session);
response.setHeader("Set-Cookie", `sid=${fresh}; HttpOnly; Secure; SameSite=Lax; Path=/`);
return session;
}
export function clientFor(session: BrowserSession): AudienceKitClient {
return new AudienceKitClient({
configuration: { host: process.env.AUDIENCEKIT_HOST, facebookAppId: process.env.FACEBOOK_APP_ID },
tokenStore: new BrowserTokenStore(session),
});
}
/** Where to send the browser to sign in with Facebook (Facebook Login for Business, with the audience's configuration). */
export async function facebookLoginUrl(client: AudienceKitClient, session: BrowserSession, redirectUri: string): Promise<string> {
const branding = await client.branding();
session.state = randomBytes(16).toString("hex");
const query = new URLSearchParams({
client_id: client.configuration.facebookAppId ?? branding.facebook_app_id ?? "",
redirect_uri: redirectUri,
state: session.state,
response_type: "code",
});
if (branding.facebook_login_config_id) query.set("config_id", branding.facebook_login_config_id);
return `https://www.facebook.com/v21.0/dialog/oauth?${query}`;
}
/** Facebook's redirect back: checks the state, then trades the code. Returns who signed in. */
export async function finishFacebookLogin(
client: AudienceKitClient,
session: BrowserSession,
callback: URL,
redirectUri: string,
deviceId: string,
): Promise<string> {
const expected = Buffer.from(session.state ?? "");
const given = Buffer.from(callback.searchParams.get("state") ?? "");
session.state = null;
if (expected.length === 0 || expected.length !== given.length || !timingSafeEqual(expected, given)) {
throw new Error("The sign-in didn't start here.");
}
const code = callback.searchParams.get("code");
if (!code) throw new Error(callback.searchParams.get("error_description") ?? "Facebook didn't sign you in.");
// The redirect URI must be exactly the one the dialog was opened with.
const credential = await client.signInWithFacebookCode(code, redirectUri, { identifier: deviceId, type: "web" });
return credential.userId;
}
if (import.meta.url === `file://${process.argv[1]}`) {
const origin = process.env.ORIGIN ?? "http://localhost:8080";
const redirectUri = `${origin}/auth/facebook`;
createServer(async (request, response) => {
const session = sessionFor(request, response);
const client = clientFor(session);
const url = new URL(request.url ?? "/", origin);
try {
if (url.pathname === "/login") {
response.writeHead(302, { Location: await facebookLoginUrl(client, session, redirectUri) }).end();
} else if (url.pathname === "/auth/facebook") {
await finishFacebookLogin(client, session, url, redirectUri, "example-server");
response.writeHead(302, { Location: "/" }).end();
} else if (url.pathname === "/logout") {
await client.signOut();
response.writeHead(302, { Location: "/" }).end();
} else {
const me = (await client.isSignedIn()) ? await client.me() : null;
response
.writeHead(200, { "Content-Type": "text/html; charset=utf-8" })
.end(me ? `Signed in as ${me.name}. <a href="/logout">Sign out</a>` : `<a href="/login">Sign in with Facebook</a>`);
}
} catch (error) {
// A session the API refused has already been forgotten: offer sign-in again.
if (error instanceof AudienceKitError && error.isUnauthenticated) response.writeHead(302, { Location: "/login" }).end();
else response.writeHead(400).end(error instanceof Error ? error.message : "Something went wrong.");
}
}).listen(8080, () => console.log(`${origin}/login`));
}
member-actions.ts
// What a signed-in member does on a site, in the order a night out goes: RSVP, add it to their calendar, buy cover,
// show the pass at the door, and report something they saw in chat.
import { AudienceKitClient, REPORT_REASONS, coverPassCode, secondsUntilNextCoverPassWindow, type Event } from "audience-kit";
/** Says they're going, and returns how many are going now. */
export async function goingTo(client: AudienceKitClient, event: Event): Promise<number> {
const rsvp = await client.rsvp(event.id, "ATTENDING");
return rsvp.count;
}
/** Links that add every event they're going to (and every event at `venueId`) to their own calendar. */
export async function calendarLinks(client: AudienceKitClient, venueId?: string) {
const feed = venueId ? await client.followVenueInCalendar(venueId) : await client.createCalendarFeed();
return { appleOrOutlook: feed.webcalUrl, google: feed.googleUrl };
}
/**
* The code to show at the door for tonight's cover at a venue, and how long it's good for. It changes every 30
* seconds, so show it as a QR code and draw it again when `refreshInSeconds` runs out; don't cache it.
*/
export async function doorPass(client: AudienceKitClient, venueId: string, now = Math.floor(Date.now() / 1000)) {
const cover = await client.venueCover(venueId);
const pass = cover?.tickets?.cover?.viewerAdmission;
if (!pass?.passSecret || pass.status !== "PAID") return null;
return { code: coverPassCode(pass.id, pass.passSecret, now), refreshInSeconds: secondsUntilNextCoverPassWindow(now) };
}
/** Reports a chat message as harassment and blocks whoever sent it. */
export async function reportHarassment(client: AudienceKitClient, messageId: string) {
return client.reportContent("MESSAGE", messageId, { reason: REPORT_REASONS[1], block: true });
}
community-export.ts
// The whole community as JSON, for a static site generator (Astro, Eleventy, Hugo) to build pages from.
//
// AUDIENCEKIT_TOKEN=<application API key> AUDIENCEKIT_HOST=hotmess.social node --experimental-strip-types community-export.ts > community.json
import {
AudienceKitClient,
colorFromHex,
colorToCss,
eventVenue,
listingName,
locationCoordinate,
type Community,
} from "audience-kit";
/** The audience's accent color as CSS, from its light theme. */
function accent(community: Community): string | null {
const hex = community.audience?.theme?.light?.find((token) => token.name === "accent")?.value;
const color = hex ? colorFromHex(hex) : null;
return color ? colorToCss(color) : null;
}
/** The parts a site renders, flattened: venues with a map point, events with their venue's name, and the accent color. */
export function exportCommunity(community: Community) {
return {
audience: community.audience?.name ?? null,
accent: accent(community),
locales: community.locales.map((locale) => ({ id: locale.id, name: locale.name })),
venues: community.venues
.filter((venue) => !venue.hidden)
.map((venue) => ({
id: venue.id,
name: listingName(venue),
locale: venue.locale?.name ?? null,
point: locationCoordinate(venue.location),
tags: venue.tags?.map((tag) => tag.name) ?? [],
})),
events: community.events.map((event) => ({ id: event.id, name: event.name, startAt: event.startAt, venue: eventVenue(event)?.name ?? null })),
};
}
if (import.meta.url === `file://${process.argv[1]}`) {
const community = await AudienceKitClient.fromEnvironment().community();
console.log(JSON.stringify(exportCommunity(community), null, 2));
}