Design the backend behind digital patient intake: versioned forms pinned to each visit, link tokens instead of patient accounts, insurance card uploads through signed URLs, an append-only access log and front desk notifications without PHI, then build it in TypeScript with the data in your own AWS or GCP account.

Digital intake replaces the clipboard at the front desk with a link sent before the visit, where the patient fills in history, medications and allergies and photographs an insurance card. The hard parts sit behind the form: the questions change between visits, the link is the only credential the patient has, the card photo is PHI the moment it is uploaded, and every time staff open an intake someone may later ask who saw it.
This guide designs that backend: versioned forms pinned to each appointment, hashed link tokens, drafts and submit, uploads to a private bucket through signed URLs, an append-only access log and front desk notifications that carry no patient details. It starts with the data model and a hand-built version on AWS, then builds it in TypeScript with Encore, with every record and file in your own AWS or GCP account.
Encore has no HIPAA certification, and nothing here makes an app compliant on its own. It creates the database, the bucket and the queues in your cloud account, where they fall under the Business Associate Agreement you sign with AWS or Google Cloud.
A clinic edits its new-patient form a few times a year, adding a question about a new medication class or splitting "address" into fields. If the form lives in one row that is edited in place, an intake opened last week shows the new questions to a patient halfway through, and a submitted intake can no longer be read against the questions that were asked. Publish each version as a new row with UNIQUE (form_key, version), never update it, and store the exact form_id on the intake when it is opened.
Answers are stored as JSONB keyed by field ID, filtered on save so a client cannot add keys the form never asked for. Required fields are checked only on submit, which lets the patient save a draft on a phone in the waiting room and finish it later. Submit is a conditional UPDATE ... WHERE status = 'open' AND expires_at > now(), so a double tap submits once and an expired link cannot submit at all.
This design does not require a patient account: the link is the credential. The token is 32 random bytes, sent once in the link and stored as a SHA-256 hash, which means a database dump does not contain working links. It expires after 72 hours here, works only while the intake is open, and opening the intake again for the same appointment rotates it, which is how "resend the link" works without a second intake.
The link should say nothing about the patient or the visit reason. "Your clinic has sent a form to complete before your visit" plus the URL is enough, since a text message or email can be read by anyone holding the phone.
A card photo is several megabytes, and sending it through the API adds memory pressure and a second copy in transit for no benefit. The backend instead creates a row in intake_documents and a signed upload URL for a key such as intake/<request_id>/<document_id>, valid for ten minutes, and the browser uploads directly to the bucket. The signed upload URL does not cap the size of the upload, so a completion call checks the stored object's size and deletes anything over the limit. Staff get download URLs that expire after five minutes, never public links.
Turn on bucket versioning so an overwrite or accidental delete can be recovered, and keep the bucket private with public access blocked.
The HIPAA Security Rule's audit controls standard in 45 CFR 164.312(b) asks for mechanisms that record and examine activity in systems holding electronic PHI, without listing fields. For intake that means one row each time a patient loads, saves or submits the form, requests or completes a document upload, and each time staff view an intake or receive document links, with the actor, the action, the intake and the patient. Those reads and writes record the row in the same transaction as the access, so a response that returned data always left a row. A BEFORE UPDATE OR DELETE trigger rejects changes to the table, and the PHI access audit log guide covers TRUNCATE, retention purges and access-history queries in depth.
CREATE TABLE intake_access_log (
id BIGSERIAL PRIMARY KEY,
at TIMESTAMPTZ NOT NULL DEFAULT now(),
actor TEXT NOT NULL, -- 'patient' or a staff ID
action TEXT NOT NULL,
request_id TEXT NOT NULL,
patient_id TEXT NOT NULL,
detail TEXT
);
CREATE TRIGGER intake_access_log_no_change
BEFORE UPDATE OR DELETE ON intake_access_log
FOR EACH ROW EXECUTE FUNCTION intake_log_append_only();
The design does not depend on a framework, and a service you run yourself on AWS can implement all of it.
intake/. If you need the size enforced by S3 itself, use a presigned POST policy with content-length-range instead of a presigned PUT.You also write the Dockerfile, the IAM policies, the networking and the pipeline, and keep them in step with the schema as the form grows.
Encore is a backend framework with built-in infrastructure, and in this service the intake database, the documents bucket and the submitted topic are TypeScript declarations next to the endpoints that use them. Deploying to your own AWS account creates RDS, a private S3 bucket, and SNS with SQS, as the AWS infrastructure docs list, or Cloud SQL, Cloud Storage and Pub/Sub on GCP. Encore provisions an IAM role for the service, or a service account on GCP, and PHI stays in that account, under your BAA.

When a coding agent adds a question type or a new document kind, the change is a migration and a few lines in the same service, and encore run starts Postgres and a local bucket so the agent can open an intake and submit it with synthetic data before anyone reviews the diff.
Run in your terminal to get started locally.
Create intake/encore.service.ts with export default new Service("intake") from encore.dev/service, and put the full schema in intake/migrations/1_intake.up.sql:
CREATE TABLE intake_forms (
id TEXT PRIMARY KEY, -- e.g. 'new-patient@3'
form_key TEXT NOT NULL,
version INT NOT NULL,
fields JSONB NOT NULL, -- [{"id": "allergies", "label": "...", "required": true}]
published_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (form_key, version)
);
CREATE TABLE intake_requests (
id TEXT PRIMARY KEY,
clinic_id TEXT NOT NULL,
appointment_id TEXT NOT NULL UNIQUE,
patient_id TEXT NOT NULL,
form_id TEXT NOT NULL REFERENCES intake_forms (id),
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL DEFAULT 'open'
CHECK (status IN ('open', 'submitted', 'reviewed')),
answers JSONB NOT NULL DEFAULT '{}'::jsonb,
submitted_at TIMESTAMPTZ
);
CREATE TABLE intake_documents (
id TEXT PRIMARY KEY,
request_id TEXT NOT NULL REFERENCES intake_requests (id),
kind TEXT NOT NULL
CHECK (kind IN ('insurance_front', 'insurance_back', 'photo_id', 'referral')),
object_key TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'stored', 'rejected')),
size_bytes BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Every read and write of intake data, by patients and staff.
CREATE TABLE intake_access_log (
id BIGSERIAL PRIMARY KEY,
at TIMESTAMPTZ NOT NULL DEFAULT now(),
actor TEXT NOT NULL, -- 'patient' or a staff ID
action TEXT NOT NULL,
request_id TEXT NOT NULL,
patient_id TEXT NOT NULL,
detail TEXT
);
CREATE FUNCTION intake_log_append_only() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'intake_access_log is append-only';
END $$;
CREATE TRIGGER intake_access_log_no_change
BEFORE UPDATE OR DELETE ON intake_access_log
FOR EACH ROW EXECUTE FUNCTION intake_log_append_only();
CREATE TABLE staff_tokens (
token_hash TEXT PRIMARY KEY,
staff_id TEXT NOT NULL,
clinic_id TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE sent_notifications (
request_id TEXT NOT NULL,
kind TEXT NOT NULL,
PRIMARY KEY (request_id, kind)
);
Staff sign in through whatever identity provider the clinic already uses. The auth handler below checks the bearer token it issued against a hashed copy, and returns the staff ID and clinic that every staff endpoint reads with getAuthData():
// intake/db.ts
import { SQLDatabase } from "encore.dev/storage/sqldb";
// Postgres locally with `encore run`; RDS or Cloud SQL in your own account when deployed.
export const db = new SQLDatabase("intake", { migrations: "./migrations" });
// intake/auth.ts
import { APIError, Gateway, Header } from "encore.dev/api";
import { authHandler } from "encore.dev/auth";
import { createHash } from "node:crypto";
import { db } from "./db";
interface AuthParams {
authorization: Header<"Authorization">;
}
export interface StaffAuth {
userID: string;
clinicID: string;
}
// Staff sign in through your identity provider; this checks the bearer
// token it issued against a hashed copy in the database.
export const staffAuth = authHandler<AuthParams, StaffAuth>(async ({ authorization }) => {
const token = authorization.replace(/^Bearer /, "");
const row = await db.queryRow<{ staff_id: string; clinic_id: string }>`
SELECT staff_id, clinic_id FROM staff_tokens
WHERE token_hash = ${sha256(token)} AND expires_at > now()`;
if (!row) throw APIError.unauthenticated("invalid staff token");
return { userID: row.staff_id, clinicID: row.clinic_id };
});
export const gateway = new Gateway({ authHandler: staffAuth });
export function sha256(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
The patient endpoints take the link token from an X-Intake-Token header, the staff endpoints require auth and filter by the staff member's clinic, and every endpoint that carries answers, tokens or signed URLs sets sensitive: true, which per the API docs redacts payloads and headers from Encore's traces:
// intake/intake.ts
import { api, APIError, Header } from "encore.dev/api";
import { getAuthData } from "~encore/auth";
import { Subscription, Topic } from "encore.dev/pubsub";
import { Bucket } from "encore.dev/storage/objects";
import log from "encore.dev/log";
import { randomBytes, randomUUID } from "node:crypto";
import { db } from "./db";
import { sha256 } from "./auth";
// Insurance cards, IDs and referrals. Private, versioned, signed URLs only.
// Endpoints that carry answers, tokens or signed URLs set sensitive: true,
// which redacts payloads and headers from traces.
const documents = new Bucket("intake-documents", { versioned: true });
// Carries IDs only, never answers, so no PHI travels through the topic.
export const submitted = new Topic<{ requestId: string; clinicId: string }>("intake-submitted", {
deliveryGuarantee: "at-least-once",
});
const LINK_TTL_MS = 72 * 60 * 60 * 1000;
const MAX_DOC_BYTES = 10 * 1024 * 1024;
type Answers = Record<string, string>;
interface Field {
id: string;
label: string;
required: boolean;
}
// Staff (or the scheduling system) open an intake for an appointment.
// The raw token goes into the patient's link; only its hash is stored.
export const openIntake = api(
{ expose: true, auth: true, method: "POST", path: "/intake-requests", sensitive: true },
async (p: { appointmentId: string; patientId: string; formKey: string }): Promise<{ requestId: string; token: string }> => {
const staff = getAuthData()!;
const form = await db.queryRow<{ id: string }>`
SELECT id FROM intake_forms WHERE form_key = ${p.formKey}
ORDER BY version DESC LIMIT 1`;
if (!form) throw APIError.notFound("no published form with that key");
const token = randomBytes(32).toString("base64url");
const expiresAt = new Date(Date.now() + LINK_TTL_MS);
// A second call for the same appointment rotates the link while the intake is open.
const row = await db.queryRow<{ id: string }>`
INSERT INTO intake_requests (id, clinic_id, appointment_id, patient_id, form_id, token_hash, expires_at)
VALUES (${randomUUID()}, ${staff.clinicID}, ${p.appointmentId}, ${p.patientId}, ${form.id}, ${sha256(token)}, ${expiresAt})
ON CONFLICT (appointment_id) DO UPDATE
SET token_hash = EXCLUDED.token_hash, expires_at = EXCLUDED.expires_at
WHERE intake_requests.status = 'open' AND intake_requests.clinic_id = EXCLUDED.clinic_id
RETURNING id`;
if (!row) throw APIError.failedPrecondition("intake already submitted for this appointment");
return { requestId: row.id, token };
},
);
interface PatientParams {
token: Header<"X-Intake-Token">;
}
interface OpenRequest {
id: string;
patient_id: string;
form_id: string;
fields: Field[];
answers: Answers;
}
async function openRequest(token: string): Promise<OpenRequest> {
const row = await db.queryRow<OpenRequest>`
SELECT r.id, r.patient_id, r.form_id, f.fields, r.answers
FROM intake_requests r JOIN intake_forms f ON f.id = r.form_id
WHERE r.token_hash = ${sha256(token)} AND r.status = 'open' AND r.expires_at > now()`;
if (!row) throw APIError.permissionDenied("this intake link is no longer valid");
return row;
}
// The patient loads the form version this intake was opened with.
export const getIntake = api(
{ expose: true, method: "GET", path: "/intake", sensitive: true },
async ({ token }: PatientParams): Promise<{ formId: string; fields: Field[]; answers: Answers }> => {
const r = await openRequest(token);
await using tx = await db.begin();
await tx.exec`
INSERT INTO intake_access_log (actor, action, request_id, patient_id)
VALUES ('patient', 'view_form', ${r.id}, ${r.patient_id})`;
await tx.commit();
return { formId: r.form_id, fields: r.fields, answers: r.answers };
},
);
// Save a draft, or submit when every required field has an answer.
export const saveIntake = api(
{ expose: true, method: "PUT", path: "/intake", sensitive: true },
async (p: PatientParams & { answers: Answers; submit: boolean }): Promise<{ status: string }> => {
const r = await openRequest(p.token);
const allowed = new Set(r.fields.map((f) => f.id));
const answers: Answers = {};
for (const [k, v] of Object.entries(p.answers)) if (allowed.has(k)) answers[k] = v;
if (p.submit) {
const missing = r.fields.filter((f) => f.required && !answers[f.id]?.trim());
if (missing.length) {
throw APIError.invalidArgument(`missing: ${missing.map((f) => f.id).join(", ")}`);
}
}
await using tx = await db.begin();
const updated = await tx.queryRow<{ status: string; clinic_id: string }>`
UPDATE intake_requests
SET answers = ${JSON.stringify(answers)}::jsonb,
status = CASE WHEN ${p.submit} THEN 'submitted' ELSE status END,
submitted_at = CASE WHEN ${p.submit} THEN now() ELSE submitted_at END
WHERE id = ${r.id} AND status = 'open' AND expires_at > now()
RETURNING status, clinic_id`;
if (!updated) throw APIError.permissionDenied("this intake link is no longer valid");
await tx.exec`
INSERT INTO intake_access_log (actor, action, request_id, patient_id)
VALUES ('patient', ${p.submit ? "submit" : "save_draft"}, ${r.id}, ${r.patient_id})`;
await tx.commit();
if (p.submit) await submitted.publish({ requestId: r.id, clinicId: updated.clinic_id });
return { status: updated.status };
},
);
const KINDS = ["insurance_front", "insurance_back", "photo_id", "referral"] as const;
// The browser uploads the file straight to the bucket with a short-lived URL.
export const requestUpload = api(
{ expose: true, method: "POST", path: "/intake/documents", sensitive: true },
async (p: PatientParams & { kind: string }): Promise<{ documentId: string; uploadUrl: string }> => {
if (!(KINDS as readonly string[]).includes(p.kind)) throw APIError.invalidArgument("unknown document kind");
const r = await openRequest(p.token);
const documentId = randomUUID();
const key = `intake/${r.id}/${documentId}`;
await using tx = await db.begin();
await tx.exec`
INSERT INTO intake_documents (id, request_id, kind, object_key)
VALUES (${documentId}, ${r.id}, ${p.kind}, ${key})`;
await tx.exec`
INSERT INTO intake_access_log (actor, action, request_id, patient_id, detail)
VALUES ('patient', 'request_upload', ${r.id}, ${r.patient_id}, ${documentId})`;
await tx.commit();
const { url } = await documents.signedUploadUrl(key, { ttl: 10 * 60 });
return { documentId, uploadUrl: url };
},
);
// Called after the upload. Signed URLs do not limit size, so check it here.
export const completeUpload = api(
{ expose: true, method: "POST", path: "/intake/documents/:documentId/complete", sensitive: true },
async (p: PatientParams & { documentId: string }): Promise<{ status: string }> => {
const r = await openRequest(p.token);
const doc = await db.queryRow<{ object_key: string }>`
SELECT object_key FROM intake_documents
WHERE id = ${p.documentId} AND request_id = ${r.id} AND status = 'pending'`;
if (!doc) throw APIError.notFound("no pending upload with that ID");
if (!(await documents.exists(doc.object_key))) throw APIError.failedPrecondition("upload not finished");
const attrs = await documents.attrs(doc.object_key);
const status = attrs.size <= MAX_DOC_BYTES ? "stored" : "rejected";
if (status === "rejected") await documents.remove(doc.object_key);
await using tx = await db.begin();
await tx.exec`
UPDATE intake_documents SET status = ${status}, size_bytes = ${attrs.size}
WHERE id = ${p.documentId}`;
await tx.exec`
INSERT INTO intake_access_log (actor, action, request_id, patient_id, detail)
VALUES ('patient', 'complete_upload', ${r.id}, ${r.patient_id}, ${p.documentId})`;
await tx.commit();
return { status };
},
);
interface StaffView {
answers: Answers;
formId: string;
submittedAt: string | null;
documents: { id: string; kind: string; url: string }[];
}
// Staff read a submitted intake. The access row is written in the same
// transaction as the read, so a view cannot happen without a log entry.
export const viewIntake = api(
{ expose: true, auth: true, method: "GET", path: "/clinic/intake/:requestId", sensitive: true },
async ({ requestId }: { requestId: string }): Promise<StaffView> => {
const staff = getAuthData()!;
await using tx = await db.begin();
const r = await tx.queryRow<{ patient_id: string; form_id: string; answers: Answers; submitted_at: Date | null }>`
SELECT patient_id, form_id, answers, submitted_at FROM intake_requests
WHERE id = ${requestId} AND clinic_id = ${staff.clinicID}`;
if (!r) throw APIError.notFound("intake not found");
const docs: { id: string; kind: string; object_key: string }[] = [];
for await (const d of tx.query<{ id: string; kind: string; object_key: string }>`
SELECT id, kind, object_key FROM intake_documents
WHERE request_id = ${requestId} AND status = 'stored'`) {
docs.push(d);
}
await tx.exec`
INSERT INTO intake_access_log (actor, action, request_id, patient_id, detail)
VALUES (${staff.userID}, 'view', ${requestId}, ${r.patient_id}, ${`${docs.length} document links`})`;
await tx.commit();
const links = await Promise.all(
docs.map(async (d) => ({
id: d.id,
kind: d.kind,
url: (await documents.signedDownloadUrl(d.object_key, { ttl: 5 * 60 })).url,
})),
);
return {
answers: r.answers,
formId: r.form_id,
submittedAt: r.submitted_at ? r.submitted_at.toISOString() : null,
documents: links,
};
},
);
// Tell the front desk a new intake is ready. The message has an ID and a
// link into your staff app, no patient details. Retries send it once.
const _ = new Subscription(submitted, "notify-front-desk", {
handler: async ({ requestId, clinicId }) => {
const first = await db.queryRow`
INSERT INTO sent_notifications (request_id, kind) VALUES (${requestId}, 'front_desk')
ON CONFLICT DO NOTHING RETURNING request_id`;
if (!first) return;
log.info("intake ready for review", { requestId, clinicId });
},
});
The code type-checks against the released encore.dev package and passes encore check, and the SQL was run against Postgres 17: reopening an open intake rotated the token hash, a second clinic could not take over the same appointment, a second submit matched no row, reopening a submitted intake returned nothing, and both UPDATE and DELETE on the access log raised an exception. The topic carries only the intake and clinic IDs, and sent_notifications makes a redelivered message a no-op; a crash between that insert and the send drops one front desk message, which the staff worklist still shows.
encore run starts Postgres locally and stores documents on disk, so the whole flow runs without an AWS account. Use synthetic patients locally and in preview environments, and only put real patient data in environments that run in the AWS or GCP account covered by your BAA.
Connect your AWS account as described in Connect your cloud account, create an environment and run git push encore. Encore builds the image, provisions RDS, S3, SNS and SQS in that account and an IAM role for the service, and runs the migrations. Accept the BAA in AWS Artifact before any real patient data reaches the environment.
Encore's security and compliance page does not list a HIPAA certification. The BAA with AWS or Google Cloud, the risk analysis, access reviews, CloudTrail and backup policies, workforce training and how long intake records are kept remain decisions for your compliance program, and Encore's part is creating the database, bucket and queues in your account the same way in every environment.
Store each published version as its own immutable row with a form key and a version number, and pin the version on the intake request when it is opened. A clinic can then change the questions for future visits without changing what an open or submitted intake asked, and staff always see answers next to the questions that were shown.
Most intake flows work without patient accounts: they send a link for one appointment that carries a random token, store only a SHA-256 hash of that token, and expire it after a few days. The token gives access to that one intake while it is open, and it stops working once the form is submitted.
Have the backend create a document row and a short-lived signed upload URL for a key under the intake's ID in a private bucket, and let the browser upload directly to object storage. After the upload, check that the object exists and is within your size limit before marking it stored, and give staff short-lived signed download URLs instead of public links.
Declare the database, the private documents bucket and the submitted topic in TypeScript next to the endpoints, mark endpoints that carry answers or signed URLs with sensitive: true, and write the access log row in the same transaction as each staff read. Deployed to your own AWS account, Encore provisions RDS, S3, and SNS with SQS, and an IAM role for the service; the BAA with AWS and your compliance program stay with your team.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.