Server
One HTTP endpoint over any store, for any framework — auth, CORS, validation, redaction, hooks and webhooks on the Fetch API.
@siteping/server turns any store into the HTTP API the widget and the dashboard talk to. It speaks the Fetch API only (Request → Response) and imports no Node built-in, so the same handler runs on Node 22+, Bun, Deno and edge workers, mounted by Next.js, Hono, Express or anything else.
npm i @siteping/serverOn Prisma, @siteping/adapter-prisma gives you this handler with the Prisma store built in — every option below works there too.
Mounting
createSitepingHandler returns one handler per HTTP method: GET, POST, PATCH, DELETE and OPTIONS. Mount all five on a single URL.
Next.js (App Router)
// app/api/siteping/route.ts
import { createSitepingHandler } from "@siteping/server";
import { store } from "@/lib/siteping-store";
export const { GET, POST, PATCH, DELETE, OPTIONS } = createSitepingHandler({
store,
apiKey: process.env.SITEPING_API_KEY,
});Hono
import { createSitepingHandler } from "@siteping/server";
import { Hono } from "hono";
import { store } from "./siteping-store";
const siteping = createSitepingHandler({ store, apiKey: process.env.SITEPING_API_KEY });
const app = new Hono();
app.on(["GET", "POST", "PATCH", "DELETE", "OPTIONS"], "/api/siteping", (c) => {
// Hono runs GET routes for HEAD too, a method SitePing does not serve.
const handle = siteping[c.req.method as keyof typeof siteping];
return handle ? handle(c.req.raw) : c.body(null, 405, { Allow: "GET, POST, PATCH, DELETE, OPTIONS" });
});
export default app;Bun.serve, Deno.serve and a Cloudflare Worker's fetch hand you every request, whatever its method — HEAD from an uptime monitor, PUT, anything: look the handler up among the five, and answer 405 to the rest:
const METHODS = ["GET", "POST", "PATCH", "DELETE", "OPTIONS"] as const;
function handleSiteping(request: Request): Response | Promise<Response> {
const method = METHODS.find((name) => name === request.method);
if (!method) return new Response(null, { status: 405, headers: { Allow: METHODS.join(", ") } });
return siteping[method](request);
}
Bun.serve({ fetch: handleSiteping });Remix and SvelteKit endpoints export a function per method: have each call its own, siteping.GET from the GET.
Express
Express hands you Node's req/res, not a Request: convert at the edge.
import { createSitepingHandler, type SitepingHandler } from "@siteping/server";
import express from "express";
import { store } from "./siteping-store";
const siteping = createSitepingHandler({ store, apiKey: process.env.SITEPING_API_KEY });
const app = express();
// Raw bytes in: the handler parses and validates the JSON itself. Screenshots
// travel inline, so allow the handler's own cap (maxBodyBytes), not body-parser's 100 kB.
app.all("/api/siteping", express.raw({ type: () => true, limit: "4mb" }), async (req, res) => {
const handle = siteping[req.method as keyof SitepingHandler];
if (!handle) {
res.set("Allow", "GET, POST, PATCH, DELETE, OPTIONS").sendStatus(405);
return;
}
const headers = new Headers();
for (const [name, value] of Object.entries(req.headers)) {
if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
}
const response = await handle(
new Request(`${req.protocol}://${req.get("host")}${req.originalUrl}`, {
method: req.method,
headers,
body: Buffer.isBuffer(req.body) && req.body.length > 0 ? new Uint8Array(req.body) : null,
}),
);
res.status(response.status);
response.headers.forEach((value, name) => res.setHeader(name, value));
res.send(Buffer.from(await response.arrayBuffer()));
});Rate limiting is not handled here: apply it in your framework or reverse proxy, on POST above all — the widget calls it from anonymous browsers.
Options
| Option | Type | Default | What it does |
|---|---|---|---|
store | SitepingStore | — | Required. Prisma, Drizzle, memory or your own |
apiKey | string | — | Enables Bearer auth. Requests send Authorization: Bearer <key> |
publicEndpoints | SitepingHttpMethod[] | ["POST", "OPTIONS"] when apiKey is set | Methods that skip auth. Passing a value replaces the default — include "POST" yourself or the widget can no longer submit |
requireAuthForDestructive | boolean | true | Without an apiKey, PATCH and DELETE answer 401. In NODE_ENV=production the factory refuses to start without an apiKey. false lifts both, production included: PATCH and DELETE, deleteAll too, are then open to anyone — only behind your own auth |
redactUnauthenticatedEmails | boolean | true | See what responses expose |
access | SitepingAccessControl | — | Your own authentication instead of the four options above — see custom access |
allowedOrigins | string[] | — | Exact-match CORS allowlist. No wildcard support — ["*"] matches nothing; unset means no CORS headers at all. Listed origins may send Content-Type, Authorization, and any custom header their preflight asks for (e.g. from the widget's headers option) |
maxBodyBytes | number | 4 MiB | Largest request body, in bytes — twice the largest submission the validation accepts. A longer one answers 413 before any of it is parsed |
webhooks | WebhookConfig | WebhookConfig[] | — | Fire on each new feedback, and on the events each one opts into — see webhooks |
waitUntil | (promise) => void | — | Keeps webhook deliveries alive after the response on serverless and edge runtimes — see webhooks |
beforeCreate | (input, context) => input | — | Rewrite a submission before it is stored — see extension points |
beforeComment | (input, context) => input | — | The same for a thread reply |
presentFeedback | (feedback, context) => feedback | — | Transform each record before it is sent |
hooks | SitepingLifecycleHooks | — | onCreated, onUpdated, onDeleting, onDeleted, onCommentCreated |
logger | { error(message, context) } | console.error | Where unexpected failures go, with the request's method and path — and for a failed hook, the feedback or deletion it concerns. Webhook failures go to their own onError instead. A logger that throws or rejects falls back to console.error. It is a SitepingLogger: the same object, with a warn method too (console, winston…), serves the stores and screenshot storages, which report degraded cases through warn |
describeError | (error) => string | undefined | — | The message of a 500 instead of "Internal server error", e.g. a "run your migrations" hint. Never return the error's own details |
logger.error(message, context) takes console's and winston's order. pino takes the context first, and serializes an error only under err: passed as is, it type-checks, then logs the message without its context. Adapt it:
import pino from "pino";
const log = pino();
createSitepingHandler({
store,
logger: { error: (message, { error, ...context }) => log.error({ err: error, ...context }, message) },
});Configuration errors
createSitepingHandler checks its options when it is created, never per request: a problem throws a SitepingConfigError whose message says how to fix it. Match it with isSitepingConfigError, exported by @siteping/server and @siteping/adapter-prisma, and branch on its stable code:
code | Thrown when |
|---|---|
CONFIG_STORE_MISSING | No store — with adapter-prisma, neither store nor prisma |
CONFIG_MAX_BODY_BYTES_INVALID | maxBodyBytes is not a positive integer |
CONFIG_OWNERSHIP_CHECK_MISSING | access.authorize over a store without verifyProjectOwnership |
CONFIG_WEBHOOK_TIMEOUT_INVALID | A webhook timeoutMs no timer holds (the message names the webhook by its origin only) |
CONFIG_API_KEY_REQUIRED | NODE_ENV=production without apiKey, access or requireAuthForDestructive: false |
The security model, honestly
- Reads are public by default. Without an
apiKey, anyone who knows the URL can list feedbacks (with emails redacted — see below). - With an
apiKey, they are not.publicEndpointsthen defaults to["POST", "OPTIONS"]: a visitor without the key can submit, butGETanswers401, so the widget shows no pins and an empty panel (it says why in the browser console, once). For reviewers without the key, setpublicEndpoints: ["GET", "POST", "OPTIONS"]: anyone with the URL and a project name can then read its feedback and threads, emails redacted. Keep the default for a submit-only widget, or sign reviewers in withaccess. - Destructive calls are not. PATCH and DELETE answer
401unless you set anapiKeyor explicitly opt out withrequireAuthForDestructive: false. In production the factory throws at startup rather than run without a key, unless you opted out (CONFIG_API_KEY_REQUIRED). That check readsprocess.env.NODE_ENV, so it only runs whereprocessexists; elsewhere the401still applies. OPTIONSis always public — preflights must work.- Cross-project checks need the store. PATCH and DELETE verify that the record belongs to the
projectNamethey name through the store's optionalverifyProjectOwnership— every bundled store and anything built oncreateCollectionStoreimplements it. A hand-written store that omits it skips the check: any caller who knows a feedbackidcan then modify it regardless ofprojectName, so implement the method (see writing an adapter) or put the endpoint behind anapiKey.
What responses expose
clientIdis stripped from every response, on feedbacks and on their comments.authorEmailis blanked unless the request carries a validAuthorization: Bearerheader — on feedbacks and on the comments of their threads. The one exception: a successfulPOSTechoes the email back to its author.
Under access, canReadAuthorEmail decides instead, for every response — POST included — and for the project the request targets.
What each requester may do
Every feedback in a response — the list, the PATCH answer, the POST answer — carries permissions, and every list carries permissions.canDeleteAll:
{ "permissions": { "canChangeStatus": false, "canDelete": false, "canComment": true, "canDeleteComment": false } }Every comment of a thread — and the answer to a posted reply — carries its own { "permissions": { "canDelete": true } }: canDeleteComment covers the whole thread, while a policy that lets authors delete only their own replies grants it reply by reply.
They say what this requester would be allowed to do, so the widget and the dashboard hide the rest instead of offering a button that answers 401 or 403. The server still checks every request.
- Under the
apiKeypolicy, an action is allowed when its method is: the key holder may do everything, and a visitor without it whatpublicEndpointsopens. With["GET", "POST", "OPTIONS"], the usual setting for a public widget, a visitor reads and replies but cannot change a status or delete. - Under
access,authorizedecides, per feedback.
Servers that predate them send none, and neither does store mode: clients then hide nothing.
Custom access
A shared key suits a site and its dashboard. When reviewers log in, pass access instead: the handler asks your code who is calling and what they may do, from the standard Request — a session cookie, a JWT, a header set by your proxy. Recipes follow for OpenID Connect providers and Better Auth.
export const { GET, POST, PATCH, DELETE, OPTIONS } = createSitepingHandler({
store,
allowedOrigins: ["https://client-site.com"],
access: {
// null (or anything falsy) → 401
authenticate: (request) => getSessionUser(request),
// false → 403
authorize: ({ principal, action, projectName }) =>
action === "create" || principal.projects.includes(projectName),
// reviewer emails are personal data
canReadAuthorEmail: (principal) => principal.isStaff,
},
});authenticateruns on every method butOPTIONS, and resolves who is calling — an object, a string or a number, never a boolean. Anything falsy (null,undefined,"",0) answers401. Atrue/falsecheck is a type error, and a plain-JavaScriptfalseanswers401too. Its return type typesprincipaleverywhere else.authorizereceives theaction(create,list,update,delete,deleteAll, andcreateComment/deleteCommentfor threads), theprojectNameand, forupdate,deleteand the comment actions, thefeedbackId— plus thecommentIdfordeleteComment. It defaults to letting every authenticated caller through. PATCH and DELETE address records by id, so the factory refuses to start with anauthorizeover a store that lacksverifyProjectOwnership— every bundled store has it.authorizealso fills inpermissions, asked withdryRun: true:update,delete,createCommentanddeleteCommentfor each feedback a response carries, anddeleteAllonce per list. Nothing is being done then — skip your audit log on dry runs. The feedback'sdeleteCommentdry run carries nocommentId, its answer covering the whole thread: a per-author rule answersfalsethere (if (!commentId) return false). Each comment of a thread so refused is then asked about with itscommentId, for that comment's ownpermissions— where the per-author rule answers. Keep it fast: a page of 50 feedbacks takes 201 dry runs, plus one per comment of a thread refused wholesale, 8 at a time — they share the response'srequest, so a policy that queries a database can cache per request, in aWeakMapkeyed on it.- A dry run is asked about an action, not a method. Its
requestis the response's — aGETfor a list, thePOSTorPATCHa write answers — andauthenticateis not called again for it. Decide byaction, never byrequest.method; and whenauthenticateadmits visitors on some methods only, haveauthorizerefuse them the other actions, or they are offered controls that answer401. canReadAuthorEmailreveals reviewer emails ontrueonly: without it, every response blanks them, and so does any other answer —undefinedfrom a principal that lacks the flag you read included. A policy that serves the public widget resolves a principal for anonymous visitors too, so being authenticated says nothing about who may read them. Its second argument,{ projectName, request }, names the project the request targets, so a role per project can scope emails too; it is asked once per request.canCommentAsTeamdecides whether a comment that asks for theteamrole keeps it; any other is stampedclient. It receives the same{ projectName, request }, for the project of the thread. It defaults to thecanReadAuthorEmailanswer for that project, so a policy that sets neither never grants it — see who speaks as the team. Once set, onlytruegrants the role.- A callback that throws answers a logged
500, before anything is written — exceptauthorizeon a dry run: that permission is refused, the failure logged, and the response goes out.
access replaces apiKey, publicEndpoints, requireAuthForDestructive and redactUnauthenticatedEmails: passing both is a type error. From a page on another origin, send the credential through the widget's headers option — the widget does not send cookies cross-origin.
CSRF protection
A browser attaches cookies to a forged cross-site request too, so under access, POST, PATCH and DELETE pass two checks before anything else runs:
- JSON only. A body without
Content-Type: application/jsonanswers415. That type forces a CORS preflight, which a foreign page fails. - Origin. With
allowedOrigins, a mutation whoseOriginis neither listed nor the endpoint's own answers403and is logged. Requests withoutOrigin— server-to-server calls, curl — pass. Behind a proxy that rewrites the request URL, list your public origin too, or same-origin calls look foreign.
Lists are also sent with Cache-Control: no-store, since they depend on who asks. The apiKey policy needs neither: its key travels in a header no forged request can set.
Recipe: OpenID Connect
When reviewers sign in with an OpenID Connect provider — Keycloak, Microsoft Entra ID, Auth0, Zitadel… — the widget and the dashboard send its access token as a bearer, and access verifies it with jose. Visitors without a token keep the public widget: they submit, read and reply, while administrators alone triage and read reviewer emails. If your app signs them in to that provider through Better Auth, use the Better Auth recipe instead.
// lib/siteping-access.ts
import type { SitepingAccessControl } from "@siteping/server";
import { createRemoteJWKSet, errors, type JWTPayload, jwtVerify } from "jose";
// Both from https://id.example.com/realms/acme/.well-known/openid-configuration
const ISSUER = "https://id.example.com/realms/acme";
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/protocol/openid-connect/certs`));
export interface Reviewer {
sub: string; // "" for a visitor without a token
name: string;
email: string;
isAdmin: boolean;
}
const VISITOR: Reviewer = { sub: "", name: "", email: "", isAdmin: false };
// Where your provider puts roles: Keycloak's realm roles here — see the table below.
function rolesOf(payload: JWTPayload): unknown {
return (payload.realm_access as { roles?: unknown } | undefined)?.roles;
}
// The key set down, slow or garbled: an outage, not a bad token.
const KEY_SET_FAILURES = new Set(["ERR_JOSE_GENERIC", "ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID"]);
export const oidcAccess: SitepingAccessControl<Reviewer> = {
async authenticate(request) {
const authorization = request.headers.get("Authorization") ?? "";
// Only a bearer is a credential: HTTP Basic on a staging site stays a visitor.
if (!/^Bearer(\s|$)/i.test(authorization)) return VISITOR;
const token = /^Bearer (\S+)$/i.exec(authorization)?.[1];
if (!token) return null;
try {
const { payload } = await jwtVerify(token, jwks, {
issuer: ISSUER,
audience: "siteping-api", // your API's, never the client id
algorithms: ["RS256", "PS256", "ES256", "EdDSA"],
requiredClaims: ["exp"],
});
if (!payload.sub) return null;
const roles = rolesOf(payload);
return {
sub: payload.sub,
name: typeof payload.name === "string" ? payload.name : "",
email: payload.email_verified === true && typeof payload.email === "string" ? payload.email : "",
isAdmin: Array.isArray(roles) && roles.includes("siteping-admin"),
};
} catch (error) {
if (error instanceof errors.JOSEError && !KEY_SET_FAILURES.has(error.code)) return null; // → 401
throw error; // → logged 500
}
},
authorize: ({ principal, action }) =>
principal.isAdmin || action === "create" || action === "list" || action === "createComment",
canReadAuthorEmail: (principal) => principal.isAdmin,
};// app/api/siteping/route.ts
export const { GET, POST, PATCH, DELETE, OPTIONS } = createSitepingHandler({
store,
// Every site the widget runs on, and the dashboard's own origin.
allowedOrigins: ["https://client-site.com", "https://inbox.example.com"],
access: oidcAccess,
// A signed-in author's name, and verified email, come from the token…
beforeCreate: (input, { principal }) => ({
...input,
authorName: principal.name || input.authorName,
authorEmail: principal.email || input.authorEmail,
}),
// …on their replies too.
beforeComment: (input, { principal }) => ({
...input,
authorName: principal.name || input.authorName,
authorEmail: principal.email || input.authorEmail,
}),
});On the client, headers runs before every request, so it always sends the current token — refreshed, or gone after a sign-out:
async function headers(): Promise<Record<string, string>> {
const token = await getAccessToken(); // from your OIDC client library
return token ? { Authorization: `Bearer ${token}` } : {};
}
initSiteping({ endpoint: "https://api.example.com/api/siteping", projectName: "acme", headers });
// Dashboard, on https://inbox.example.com:
// <SitepingInbox endpoint="https://api.example.com/api/siteping" projects="acme" headers={headers} />- An access token, never an ID token.
audienceis the identifier your provider puts inaudfor your API — Auth0's API identifier, or the audience a Keycloak audience mapper adds. An ID token is addressed to your client application instead, so it answers401. Auth0 issues a JWT access token only for an API audience, and Zitadel only when the application's token type is JWT. - No bearer, a visitor; a bad one, a
401. Without aBearertoken the request is anonymous, so the public widget keeps working — also behind HTTP Basic auth, whose credentials a staging site's browser or proxy attaches to every request. A malformed, expired, forged or foreign token answers401instead of being downgraded to a visitor: a reviewer whose session lapsed sees it, and the client can refresh the token. - An unreachable provider, a
500. When the key set cannot be fetched — network error, timeout, non-200answer, no key set in it —authenticatethrows: the handler logs it and answers500rather than calling every token invalid. Visitors, who send none, are unaffected. jose caches the keys and refetches them for an unknownkid, so key rotation needs nothing. - Pinned algorithms, over HTTPS.
algorithmslists what your provider signs with, so an unsigned orHS256token is refused before any key is looked up. Keep the issuer and the key set onhttps://: whoever can tamper with the key set can mint administrator tokens. - The author comes from the token.
beforeCreatestamps its name, and its email only whenemail_verifiedis true; otherwise the widget's values stay.beforeCommentdoes the same for replies, so no one signed in replies under another reviewer's name. Access tokens don't always carry these claims, so passidentityto spare signed-in users the widget's identity prompt. - Emails stay with administrators. Since
canReadAuthorEmailis set, it also decides who speaks as the team: administrators' replies are markedteam, everyone else'sclient. - One role, every project. This
authorizenever readsprojectName:siteping-admintriages every project the endpoint serves, and anyone — visitor or member — lists any of them, screenshots and diagnostics included. To keep several clients apart, give each project its own role, such assiteping-admin:acme: keep the caller's roles in the principal, and haveauthorizetestroles.includes(`siteping-admin:${projectName}`)where it testsisAdmin. Do the same incanReadAuthorEmail, whose second argument names the project:(principal, { projectName }) => principal.roles.includes(`siteping-admin:${projectName}`). To put reads behind sign-in too, returnnullinstead ofVISITORwhen no bearer comes — every request then needs a token, submissions included — and allowliston the caller's projects only.
Roles are provider-specific, so rolesOf is yours to write:
| Provider | Roles in the access token | rolesOf(payload) returns |
|---|---|---|
| Keycloak | realm_access.roles (realm roles), resource_access.<client>.roles (client roles) | As above |
| Microsoft Entra ID | roles (app roles) | payload.roles |
| Auth0 | None by default: add a claim in a post-login Action, e.g. https://siteping.example/roles | payload["https://siteping.example/roles"] |
| Zitadel | urn:zitadel:iam:org:project:roles, an object keyed by role | Object.keys(payload["urn:zitadel:iam:org:project:roles"] ?? {}) |
| Better Auth (jwt plugin) | role, comma-separated | typeof payload.role === "string" ? payload.role.split(",") : [] |
Letting authors delete their own feedback
The store records no owner: keep your own table, filled by onCreated, which sees the principal, and read by authorize. A list asks about every feedback it carries — 50 delete dry runs for a page of 50 — so read the caller's ids once per request, in a WeakMap keyed on it:
const ownerships = new WeakMap<Request, Promise<Set<string>>>();
/** The ids `sub` submitted, read once per request. */
function submittedBy(request: Request, sub: string): Promise<Set<string>> {
let ids = ownerships.get(request);
if (!ids) {
ids = db.feedbackOwner
.findMany({ where: { sub }, select: { feedbackId: true } })
.then((rows) => new Set(rows.map((row) => row.feedbackId)));
ownerships.set(request, ids);
}
return ids;
}
export const { GET, POST, PATCH, DELETE, OPTIONS } = createSitepingHandler({
store,
// …allowedOrigins, beforeCreate and beforeComment as in route.ts above
access: {
...oidcAccess,
authorize: async ({ principal, action, feedbackId = "", request }) =>
principal.isAdmin ||
action === "create" ||
action === "list" ||
action === "createComment" ||
(action === "delete" && principal.sub !== "" && (await submittedBy(request, principal.sub)).has(feedbackId)),
},
hooks: {
onCreated: async (feedback, { principal }) => {
if (principal.sub) await db.feedbackOwner.create({ data: { sub: principal.sub, feedbackId: feedback.id } });
},
},
});onCreated never fails a submission: if its write fails, that author just cannot delete the feedback. A sub is unique per issuer only — with several providers, key the table on both — and onDeleted is the place to drop rows.
Recipe: Better Auth
When your app signs users in with Better Auth, access asks it for the session: the widget and a <SitepingInbox /> mounted in the app send its cookie with every request, so the client side needs no token. Its admin plugin tells administrators apart — they triage and read reviewer emails — while everyone else, signed in or not, submits, reads and replies.
This also covers an app that signs users in to an OpenID Connect provider — Keycloak, Microsoft Entra ID, Auth0… — through Better Auth's Generic OAuth or SSO plugin: those users hold a Better Auth session too. Keep the OpenID Connect recipe for access tokens the endpoint verifies itself.
// lib/auth.ts — your Better Auth server
import { betterAuth } from "better-auth";
import { admin } from "better-auth/plugins";
export const auth = betterAuth({
// …database, emailAndPassword, socialProviders as you have them
plugins: [admin()],
});// lib/siteping-access.ts
import type { SitepingAccessControl } from "@siteping/server";
import { auth } from "@/lib/auth";
export interface Reviewer {
id: string; // "" for a visitor without a session
name: string;
email: string;
isAdmin: boolean;
}
const VISITOR: Reviewer = { id: "", name: "", email: "", isAdmin: false };
export const betterAuthAccess: SitepingAccessControl<Reviewer> = {
async authenticate(request) {
const session = await auth.api.getSession({
headers: request.headers,
// Read from the database, never renewed here — see below.
query: { disableCookieCache: true, disableRefresh: true },
});
// No session: a visitor — unless the request sent a bearer token, which then answers 401.
if (!session) return /^Bearer(\s|$)/i.test(request.headers.get("Authorization") ?? "") ? null : VISITOR;
const { user } = session;
return {
id: user.id,
name: user.name,
email: user.emailVerified ? user.email : "",
// The admin plugin stores several roles comma-separated.
isAdmin: user.role?.split(",").includes("admin") ?? false,
};
},
authorize: ({ principal, action }) =>
principal.isAdmin || action === "create" || action === "list" || action === "createComment",
canReadAuthorEmail: (principal) => principal.isAdmin,
};// app/api/siteping/route.ts
import { createSitepingHandler } from "@siteping/server";
import { betterAuthAccess } from "@/lib/siteping-access";
import { store } from "@/lib/siteping-store";
export const { GET, POST, PATCH, DELETE, OPTIONS } = createSitepingHandler({
store,
access: betterAuthAccess,
// A signed-in author's name, and verified email, come from the session…
beforeCreate: (input, { principal }) => ({
...input,
authorName: principal.name || input.authorName,
authorEmail: principal.email || input.authorEmail,
}),
// …on their replies too.
beforeComment: (input, { principal }) => ({
...input,
authorName: principal.name || input.authorName,
authorEmail: principal.email || input.authorEmail,
}),
});The session also spares signed-in users the widget's identity prompt: pass it as identity. useSiteping follows re-renders, so a sign-in or a sign-out applies to the next feedback or reply, with no remount:
// app/feedback.tsx — mounted in your root layout
"use client";
import type { SitepingIdentity } from "@siteping/widget";
import { useSiteping } from "@siteping/widget/react";
import { authClient } from "@/lib/auth-client"; // createAuthClient() from "better-auth/react"
function Widget({ identity }: { identity: SitepingIdentity | undefined }) {
useSiteping({ endpoint: "/api/siteping", projectName: "acme", identity });
return null;
}
export function Feedback() {
const { data: session, isPending } = authClient.useSession();
if (isPending) return null;
const user = session?.user;
return <Widget identity={user && { name: user.name, email: user.email }} />;
}- No session, a visitor; a dead token, a
401. Without a session the request is anonymous, so the public widget keeps working — also for someone whose cookie outlived a sign-out, an expiry or a ban, since the browser keeps sending it. A request whoseBearertoken opens no session answers401instead: its client sent the token on purpose, and learns it no longer works. Any otherAuthorizationstays a visitor: on a staging site behind HTTP Basic auth, the browser or the proxy attaches those credentials to every request. - A database outage, a
500. When Better Auth cannot read its sessions,getSessionthrows: the handler logs it and answers500rather than downgrading everyone to a visitor. Visitors without a session cookie never reach the database. - Read, never renewed. A session older than Better Auth's
updateAgegets renewed by the nextgetSession, which writes a later expiry and sets a new cookie — on a response SitePing never sends, so the browser's cookie would expire first.disableRefreshleaves the renewal to your app's own requests. - A demotion applies at once. With Better Auth's
session.cookieCacheon,getSessiontrusts the cached cookie until itsmaxAge: a role change or a revoked session would wait for it.disableCookieCachereads yourdatabaseorsecondaryStorageinstead, asgetSessiondoes anyway without the cache. Without either, Better Auth is stateless and the signed cookie is the only session record: another instance — a serverless invocation, a replica — finds no session behind that flag, and serves your administrators as visitors. DropdisableCookieCachethere; a demotion then waits for the cookie'smaxAge. - Administrators by role.
isAdminreads the admin plugin'srole—setRolewith["user", "admin"]stores"user,admin". The plugin'sadminUserIdsopens its own endpoints to users whatever their role: give those users theadminrole too. To let someone triage without the plugin's user management, give them a role of your own (declared in the plugin'sroles, if you configured some) and test that one. - The author comes from the session.
beforeCreatestamps the user's name, and their email onceemailVerifiedis true; otherwise the widget's value stays.beforeCommentdoes the same for replies. - Emails stay with administrators. Since
canReadAuthorEmailis set, it also decides who speaks as the team: administrators' replies from the inbox are markedteam, everyone else'sclient. - Cookies, and CSRF. A browser attaches the session cookie to a forged cross-site request too; the CSRF checks stop those, with nothing to configure.
- One role, every project. As in the OpenID Connect recipe,
admintriages every project the endpoint serves and anyone lists any of them. To keep several clients apart, load the caller's projects inauthenticate— for instance the slugs of their organizations, with Better Auth's organization plugin — and haveauthorizecheckprojectNameagainst them. To put reads behind sign-in too, returnnullinstead ofVISITOR— every request then needs a session, submissions included. - Authors deleting their own feedback. The OpenID Connect recipe's owner table works as is, with
principal.idwhere it readsprincipal.sub— a Better Auth user id is unique in your app, so one column is enough.
From another origin
On another origin — the widget on a client's site — a page reaches your app without its cookie: the widget sends cookies to its own origin only. Add Better Auth's bearer plugin and send the session token with headers; the recipe needs no change, since the plugin turns the token back into the session getSession reads.
// lib/auth.ts
import { admin, bearer } from "better-auth/plugins";
export const auth = betterAuth({
// …
plugins: [admin(), bearer()],
trustedOrigins: ["https://client-site.com"], // where users sign in from
});
// app/api/siteping/route.ts
export const { GET, POST, PATCH, DELETE, OPTIONS } = createSitepingHandler({
store,
// Every site the widget runs on. The inbox stays on the endpoint's own origin.
allowedOrigins: ["https://client-site.com"],
access: betterAuthAccess,
// …beforeCreate and beforeComment as above
});The token arrives in the set-auth-token header of the sign-in response; the plugin's documentation shows how to keep it. On the page, headers sends it with every request, and onError drops it once it stops working:
function headers(): Record<string, string> {
const token = localStorage.getItem("bearer_token"); // where your auth client keeps it
return token ? { Authorization: `Bearer ${token}` } : {};
}
initSiteping({
endpoint: "https://app.example.com/api/siteping",
projectName: "acme",
headers,
onError: (error) => {
// A dead token, not a 403 refusal: drop it, and the next request goes out as a visitor.
if ((error as { status?: number }).status === 401) localStorage.removeItem("bearer_token");
},
});- The token is the whole session. It is the session cookie's value, not a SitePing credential: it opens every Better Auth endpoint of your app, the admin plugin's included, from any origin, and whoever holds it keeps it alive, since Better Auth renews the session as it is used. Kept in
localStorage, it is readable by every script on that page. So have administrators triage from the inbox mounted in your app, which sends the cookie, out of scripts' reach, and keeps their session on your origin; keep the bearer for reviewers who sign in on the client's site. - Drop it once it stops working. A stale cookie stays a visitor, but a dead token answers
401to every request, submissions included, and nothing removes it fromlocalStoragewhen the session expires or is revoked. Remove it on a401, as above, and when the user signs out — not on everyAUTHerror: a403meansauthorizerefused that request, a project the reviewer isn't a member of, and the token still opens their session in your app.
When the SitePing endpoint runs apart from Better Auth — another service, an edge worker away from your database — verify tokens from Better Auth's jwt plugin with the OpenID Connect recipe instead. The page fetches one from /api/auth/token with its session cookie and sends it with headers. ISSUER and audience are your Better Auth URL, unless you set the plugin's jwt.issuer and jwt.audience; the key set is at /api/auth/jwks, and tokens are signed EdDSA. The payload is the user record: rolesOf reads role (see the table above), administrators hold admin, and the email's verification is in emailVerified, not email_verified.
Extension points
createSitepingHandler({
store,
access,
// Take the author from the session, and scrub tokens pasted in the message.
beforeCreate: (input, { principal }) => ({
...input,
authorName: principal.name,
authorEmail: principal.email,
message: input.message.replace(/token=\S+/g, "token=[redacted]"),
}),
// The same for a reply in a thread.
beforeComment: (input, { principal }) => ({
...input,
authorName: principal.name,
authorEmail: principal.email,
body: input.body.replace(/token=\S+/g, "token=[redacted]"),
}),
hooks: {
onCreated: (feedback) => searchIndex.add(feedback),
// Throw to keep the record: the DELETE answers 502 and can be retried.
onDeleting: (target) => searchIndex.remove(target),
},
});beforeCreateruns on the validated submission, beforeauthorize— which sees the project it returns.beforeCommentdoes the same for a reply,projectNameandfeedbackIdincluded — so it runs before the feedback is looked up too, and may run for one that turns out not to exist. TheauthorRoleit returns stays a claim,teambeing kept only for a caller your policy vouches for. Without it, a reply keeps the name and email its client sent.presentFeedbackruns on each record just before it is sent;clientIdstripping and email redaction still apply after it.onCreated,onUpdated,onDeletedandonCommentCreatedare awaited before the response, so serverless runtimes don't cut them off. A throw is logged and never fails the request: the write already happened.onCreatedruns once per stored feedback andonCommentCreatedonce per stored reply — the comment record with theprojectNameof its feedback — never for a replayedclientId.onCommentCreatedneeds a store implementingaddCommentIfAbsent, which tells a new reply from a retried one: every bundled store does, and the handler refuses to start without it.onDeletingruns before the delete, with{ kind: "single", id, projectName }or{ kind: "project", projectName }. A throw keeps the record and answers502.
These callbacks get { request, principal } as their context; principal is null under the apiKey policy. Hooks written as class methods keep their this.
To keep one GitHub or GitLab issue per feedback, closed and reopened along with it, @siteping/integration-issues builds these hooks for you.
HTTP reference
One endpoint, five methods. All bodies are JSON.
| Method | Purpose | Success |
|---|---|---|
POST | Create feedback (widget submissions) — or a comment, when the body has a feedbackId | 201 + record. A replayed clientId returns the existing record instead of failing (and never notifies webhooks or onCreated twice); a clientId already used by another project is refused with 409 |
GET | List feedbacks, each with its thread and permissions | 200 + { feedbacks, total, protocol, capabilities, permissions }, with Cache-Control: private, max-age=5 (no-store under access) |
PATCH | Change a status | 200 + updated record |
DELETE | Delete one or all — or a comment, when the body has a commentId | 200 + { deleted: true } |
OPTIONS | CORS preflight | 204 |
GET query parameters: projectName (required), page (default 1), limit (default 50, max 100), type, status, statuses (comma-separated list, max 4 — e.g. statuses=open,in_progress), search, url, urlPattern.
PATCH body: { id, projectName, status } — all three required. status is one of open, in_progress, resolved, wont_fix. The server derives resolvedAt automatically: set when the status is closed (resolved/wont_fix), cleared otherwise.
DELETE body: { id, projectName } for one record, or { projectName, deleteAll: true } for everything in the project.
Errors: invalid JSON → 400 { error }; validation failure → 400 { errors: [{ field, message }] }, the first 20 issues; a body over maxBodyBytes → 413; missing or wrong credentials → 401; refused by authorize or a CSRF check → 403; not JSON under access → 415; unknown id → 404; clientId owned by another project, a comment's clientId already used on another feedback, or a client comment on a full thread → 409 { error }; a value longer than the store holds (a MySQL column sync has not widened yet) → 422 { error }; comment write on a store without comments → 501 { error }; onDeleting threw → 502; anything else → 500 { error: "Internal server error" }, or the message describeError returns.
Wire protocol
The protocol ships with @siteping/server as an OpenAPI 3.1 document, generated from the schemas the handler validates with and checked against the types it sends — a client generator, a mock server or an API explorer can read it:
import spec from "@siteping/server/openapi.json" with { type: "json" };Every list response carries protocol, the version of the protocol the server speaks (SITEPING_PROTOCOL_VERSION, exported by @siteping/server: 1). It rises with each addition a client may rely on, so a client checks protocol >= N before using what version N added, rather than probing for fields. Servers that predate it send none: read that as 0.
What 1.x keeps stable:
- One endpoint, routed by method and body. A
POSTbody with afeedbackIdposts a comment, any other creates a feedback; aDELETEbody with acommentIddeletes a comment, any other deletes feedback. A payload of one resource never carries the other's key. DELETEcarries a JSON body.fetchsends it and every runtime the handler targets reads it, but HTTP gives such a body no defined meaning, and some proxies drop it — the request then answers400. Keep the endpoint behind a proxy that forwards it.- Three
409s, none worth a retry: a feedback whoseclientIdanother project already uses; a comment whoseclientIdis already used on another feedback; aclientcomment on a thread that holds 100 of them. - Status codes and JSON shapes are the contract,
errorstrings are not. They are English and informational, and a minor release may reword one: branch on the status. - Widget and dashboard 1.x need a 1.x server —
@siteping/serveror@siteping/adapter-prisma, protocol 1. Within 1.x they use what a later protocol version adds only after readingprotocol, so a newer widget keeps working against an older 1.x server.
Validation limits worth knowing
The whole body ≤ maxBodyBytes (4 MiB) · message ≤ 5000 chars · annotations ≤ 50 per feedback · comment body ≤ 5000 chars, 100 client comments per thread (team replies are not capped) · screenshotDataUrl ≤ 1.5 MB, JPEG/PNG/WebP only · diagnostics ≤ 50 console + 20 network entries · projectName ≤ 191 chars · clientId ≤ 191 chars and matches [a-zA-Z0-9_-]+ · authorEmail matches the same Unicode-aware pattern as the widget's identity modal (françois@exemple.fr is fine), so an address the modal accepts is never rejected here.
Webhooks
Get pinged on every new feedback — and, for the webhooks that opt in, on status changes, deletions and replies:
createSitepingHandler({
store,
webhooks: [
{ url: process.env.SLACK_WEBHOOK_URL!, type: "slack" },
{ url: "https://my-api.dev/hooks/siteping", type: "generic", headers: { "x-secret": "…" } },
],
});type is "slack", "discord", or "generic" (default — posts the record as JSON with the author's email unredacted, so treat generic webhook targets as trusted; clientId is stripped like everywhere else, from its comments too, and GenericWebhookPayload types the body as the receiver parses it, dates as ISO strings). Each call has a 5-second timeout by default — set timeoutMs per webhook, a positive integer up to 2,147,483,647, the longest delay a timer holds; the factory throws on any other value. Failures never block the submission, and an optional onError(err, feedbackId, { event, projectName }) lets you log them — feedbackId is "" for a project-wide deletion; an async one is awaited, and its own failure is reported to console.warn. A replayed clientId never fires them again, and two overlapping submissions of the same clientId (the widget retrying a request that timed out) notify once when they reach the same server process. Across several instances only the store can tell them apart: Prisma's @unique on clientId does, and so does the unique index of the Drizzle store. The memory and localStorage stores, like any store built on createCollectionStore, deduplicate only within one store instance, and a custom store that returns the existing record on a duplicate may notify twice unless it implements createFeedbackIfAbsent atomically — see Writing an adapter.
Deliveries are not awaited: the widget gets its answer first. A serverless or edge runtime may freeze or cancel that work once the response is out, so hand it over with waitUntil:
import { after } from "next/server";
createSitepingHandler({ store, webhooks, waitUntil: after });waitUntil from @vercel/functions or from cloudflare:workers works the same way — pass a standalone function, not an unbound method.
Feedback text is typed by anonymous visitors, so the chat payloads are hardened: Slack text is escaped (a comment containing <!channel> is shown literally, never as a notification) and Discord messages are sent with mention parsing disabled (allowed_mentions: { parse: [] }) and their markdown escaped (a [Reset your password](https://…) masked link is shown as typed, never as a disguised link) — a public form can't be used to ping your whole server or phish it. Long values are truncated to Slack's and Discord's size limits (after escaping), so a 2000-character page URL never gets the whole notification rejected.
Events
Every delivery names what happened in its X-Siteping-Event header. A webhook receives feedback.created alone unless its events says otherwise, so a webhook set up before events existed gets exactly the deliveries it always did:
createSitepingHandler({
store,
webhooks: [
{ url: process.env.SLACK_WEBHOOK_URL!, type: "slack" }, // feedback.created only
{
url: "https://my-api.dev/hooks/siteping",
events: ["feedback.created", "feedback.status_changed", "feedback.deleted", "comment.created"],
},
],
});| Event | Fires after | Generic body |
|---|---|---|
feedback.created | A feedback is stored — never for a replayed clientId | The record (GenericWebhookPayload) |
feedback.status_changed | A PATCH sets a status — even the one the feedback already had: the store keeps no previous status to compare with | The record as stored after the write, same shape |
feedback.deleted | One feedback is deleted, or every feedback of a project (deleteAll) — which fires even for a project that held nothing, stores report no count | { kind: "single", id, projectName } or { kind: "project", projectName }, as onDeleting receives it |
comment.created | A reply is stored — never for a replayed or racing clientId | The comment, clientId stripped, plus the projectName of its feedback (GenericWebhookCommentPayload) |
Slack and Discord get a message of their own for each event ("Feedback resolved: bug from Alice", "New client reply from Bob"), escaped like a feedback's. A delivery fires only once its write has succeeded: never for a request refused by validation, auth or the ownership check, nor for an unknown id. GenericWebhookEventMap types each generic body by event, and WEBHOOK_EVENTS lists the events, to check the header against. events must be a non-empty list of known events — the factory throws otherwise — and comment.created needs a store implementing addCommentIfAbsent, like onCommentCreated.