Quickstart
Add the tables, mount the API, and render a survey.
Setup is Better Auth–like: add the tables, create the instance, and mount the handler.
Install
npm i @dimah-survey/server @dimah-survey/db @dimah-survey/react survey-core survey-react-uiAdd the tables
Add the tables, migrate, and export database.
Create the server
import { dimahSurvey } from "@dimah-survey/server";
import { database } from "@/db";
export const editor = dimahSurvey({
audience: "editor",
database,
guard: async () => {
// Authorize the editor.
},
});
export const fill = dimahSurvey({
audience: "fill",
database,
guard: async () => {
// Return { respondentId } or { anonymous: true }.
return { anonymous: true };
},
});Publish a survey
Call this once at startup so there is a survey to fill. In the product, create and publish through the editor API.
import { database } from "@/db";
const definition = {
title: "Welcome",
pages: [
{
name: "welcome",
elements: [
{ type: "text", name: "name", title: "Your name", isRequired: true },
{
type: "rating",
name: "score",
title: "How was it?",
isRequired: true,
},
],
},
],
};
export async function seedWelcomeSurvey() {
if (await database.getSurvey("welcome")) return;
await database.saveSurvey({
id: "welcome",
slug: "welcome",
draftJson: definition,
});
await database.publishSurvey({ id: "welcome" });
}Mount the handlers
Fill is /api/survey. Editor is /api/admin/survey.
import { toNextJsHandler } from "@dimah-survey/server/next";
import { fill } from "@/lib/survey";
export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(fill);import { toNextJsHandler } from "@dimah-survey/server/next";
import { editor } from "@/lib/survey";
export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(editor);Mount Express before express.json(). Keep Fastify's JSON parser off these
paths.
Start the response
import { headers } from "next/headers";
import { fill } from "@/lib/survey";
export async function startWelcomeResponse() {
const response = await fill.api.startResponse({
body: { surveyId: "welcome" },
headers: await headers(),
});
return response.id;
}Render the survey
import { Survey } from "survey-react-ui";
import { createFillClient, useSurveyResponse } from "@dimah-survey/react";
import "survey-core/survey-core.min.css";
const client = createFillClient({ baseURL: "/api/survey" });
export function Fill({ responseId }: { responseId: string }) {
const { model, error, saveError, stale, reload } = useSurveyResponse({
client,
responseId,
});
if (error) return <p>{error.message}</p>;
if (!model) return <p>Loading…</p>;
return (
<>
{saveError ? <p>{saveError.message}</p> : null}
{stale ? <button onClick={reload}>Reload</button> : null}
<Survey model={model} />
</>
);
}