Updated Nov 27, 20268 min read

Build a Patient Intake Forms Backend

How to collect pre-visit intake forms with saved drafts, insurance card uploads, a guarded submit step, an idempotent hand-off to the EHR and an audit trail of who opened each form, with PHI kept in your own cloud account.

Illustration for Build a Patient Intake Forms Backend

A patient intake form starts as a page of fields and a submit button. It becomes a backend once answers have to survive a half-finished session, an insurance card photo needs a private home, and the same data must reach the EHR exactly once.

This guide builds that service: drafts that save as the patient types, a submit step that cannot run twice, an upload path for card images, an idempotent hand-off to the EHR and an audit row for every read.

What does an intake backend need?

PieceWhat to decide
FormsOne intake per appointment, created once even if the link is opened twice
DraftsAnswers saved as the patient types, merged into one JSON column while the form is open
UploadsInsurance card and ID images sent straight to a private bucket with short-lived URLs
SubmitA single guarded transition from draft to submitted, after which patients cannot edit
EHR hand-offAsynchronous, retried, and safe to repeat
AuditA record of who read or changed each form, written with the read itself

The HIPAA Security Rule asks for audit controls and access controls on systems with electronic PHI, and the minimum necessary standard is a reason to keep each staff view limited to the fields that role needs. AWS will sign a Business Associate Addendum and lists HIPAA-eligible services, but a BAA is required before you store PHI, and it is your responsibility to put that agreement in place and to confirm that every service in the path is eligible. Which controls your organization must meet is a decision for your compliance team. Running the backend in your own account does not make the setup HIPAA compliant on its own.

How do you build it without a framework?

Each state change is one guarded statement: creating an intake uses an upsert on the appointment id so that a second click returns the existing form, saving a draft only touches rows still in draft, and submitting moves draft to submitted once. The EHR push reads the row and sends the intake id as an idempotency key, so a redelivered message cannot create a second record. Around that you need a queue with retries, a private bucket with a policy for the service, a database with encryption and backups, and a place for secrets. Teams bring their own agents, and Encore provides the environments, the system context and the controls for that infrastructure.

How does Encore build the intake service?

Encore brings infrastructure from code, so the intake database, the upload bucket and the submit topic are declared next to the endpoints and created in your own AWS or GCP account on deploy. The AWS docs list RDS, S3, Fargate and SNS with SQS, and the GCP docs list Cloud SQL, Cloud Storage, Cloud Run and Pub/Sub.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create clinic --example=hello-world$ cd clinic && mkdir -p intake/migrations

The service creates an intake per appointment, saves drafts, hands out an upload URL for the card image, submits the form, lets staff read it with an audit row and pushes it to the EHR from a subscriber:

// intake/intake.go package intake import ( "context" "encoding/json" "errors" "strconv" "strings" "time" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/rlog" "encore.dev/storage/objects" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("intake", sqldb.DatabaseConfig{Migrations: "./migrations"}) var cards = objects.NewBucket("insurance-cards", objects.BucketConfig{}) type Submitted struct { IntakeID int64 `json:"intake_id"` } var submitted = pubsub.NewTopic[*Submitted]("intake-submitted", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type CreateParams struct { AppointmentID string `json:"appointment_id"` PatientRef string `json:"patient_ref"` } type CreateResponse struct { ID int64 `json:"id"` Status string `json:"status"` } // Create returns the existing intake when the link is opened twice. // //encore:api public method=POST path=/intakes func Create(ctx context.Context, p *CreateParams) (*CreateResponse, error) { if strings.TrimSpace(p.AppointmentID) == "" || strings.TrimSpace(p.PatientRef) == "" { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "appointment_id and patient_ref are required"} } var r CreateResponse err := db.QueryRow(ctx, ` INSERT INTO intakes (appointment_id, patient_ref) VALUES ($1, $2) ON CONFLICT (appointment_id) DO UPDATE SET appointment_id = EXCLUDED.appointment_id RETURNING id, status`, p.AppointmentID, p.PatientRef).Scan(&r.ID, &r.Status) if err != nil { return nil, err } return &r, nil } type DraftParams struct { Answers map[string]string `json:"answers"` } // SaveDraft merges answers while the form is still a draft. // //encore:api public method=PUT path=/intakes/:id/answers func SaveDraft(ctx context.Context, id int64, p *DraftParams) error { body, err := json.Marshal(p.Answers) if err != nil { return err } res, err := db.Exec(ctx, ` UPDATE intakes SET answers = answers || $2::jsonb, updated_at = now() WHERE id = $1 AND status = 'draft'`, id, string(body)) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.FailedPrecondition, Message: "intake is not editable"} } return nil } type CardURL struct { URL string `json:"url"` } // CardUploadURL lets the browser upload a card image straight to the private bucket. // //encore:api public method=POST path=/intakes/:id/card-url func CardUploadURL(ctx context.Context, id int64) (*CardURL, error) { u, err := cards.SignedUploadURL(ctx, "intake-"+itoa(id)+"/card", objects.WithTTL(10*time.Minute)) if err != nil { return nil, err } return &CardURL{URL: u.URL}, nil } // Submit moves the form from draft to submitted exactly once. // //encore:api public method=POST path=/intakes/:id/submit func Submit(ctx context.Context, id int64) error { var missing bool err := db.QueryRow(ctx, ` SELECT NOT (answers ? 'date_of_birth' AND answers ? 'reason_for_visit') FROM intakes WHERE id = $1`, id).Scan(&missing) if errors.Is(err, sqldb.ErrNoRows) { return &errs.Error{Code: errs.NotFound, Message: "intake not found"} } if err != nil { return err } if missing { return &errs.Error{Code: errs.InvalidArgument, Message: "date_of_birth and reason_for_visit are required"} } res, err := db.Exec(ctx, ` UPDATE intakes SET status = 'submitted', submitted_at = now() WHERE id = $1 AND status = 'draft'`, id) if err != nil { return err } if res.RowsAffected() == 0 { return nil // already submitted } _, err = submitted.Publish(ctx, &Submitted{IntakeID: id}) return err } type Intake struct { ID int64 `json:"id"` PatientRef string `json:"patient_ref"` Status string `json:"status"` Answers json.RawMessage `json:"answers"` SubmittedAt *time.Time `json:"submitted_at,omitempty"` } // Read returns a form to staff and records the access in the same transaction. // //encore:api private method=GET path=/intakes/:id/staff/:actor func Read(ctx context.Context, id int64, actor string) (*Intake, error) { tx, err := db.Begin(ctx) if err != nil { return nil, err } defer tx.Rollback() var in Intake err = tx.QueryRow(ctx, ` SELECT id, patient_ref, status, answers, submitted_at FROM intakes WHERE id = $1`, id). Scan(&in.ID, &in.PatientRef, &in.Status, &in.Answers, &in.SubmittedAt) if errors.Is(err, sqldb.ErrNoRows) { return nil, &errs.Error{Code: errs.NotFound, Message: "intake not found"} } if err != nil { return nil, err } if _, err := tx.Exec(ctx, ` INSERT INTO intake_audit (intake_id, actor, action) VALUES ($1, $2, 'read')`, id, actor); err != nil { return nil, err } if err := tx.Commit(); err != nil { return nil, err } return &in, nil } var _ = pubsub.NewSubscription(submitted, "push-to-ehr", pubsub.SubscriptionConfig[*Submitted]{ Handler: func(ctx context.Context, m *Submitted) error { var status string if err := db.QueryRow(ctx, `SELECT status FROM intakes WHERE id = $1`, m.IntakeID).Scan(&status); err != nil { return err } if status == "synced" { return nil } // Call the EHR here with the intake id as the idempotency key. rlog.Info("push intake to EHR", "idempotency_key", m.IntakeID) _, err := db.Exec(ctx, ` UPDATE intakes SET status = 'synced', synced_at = now() WHERE id = $1 AND status = 'submitted'`, m.IntakeID) return err }, RetryPolicy: &pubsub.RetryPolicy{MinBackoff: 10 * time.Second, MaxBackoff: 10 * time.Minute, MaxRetries: 8}, }) func itoa(n int64) string { return strconv.FormatInt(n, 10) }
-- intake/migrations/1_create_intakes.up.sql CREATE TABLE intakes ( id BIGSERIAL PRIMARY KEY, appointment_id TEXT NOT NULL UNIQUE, patient_ref TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'submitted', 'synced')), answers JSONB NOT NULL DEFAULT '{}', submitted_at TIMESTAMPTZ, synced_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE intake_audit ( id BIGSERIAL PRIMARY KEY, intake_id BIGINT NOT NULL REFERENCES intakes (id), actor TEXT NOT NULL, action TEXT NOT NULL, at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX intake_audit_intake_idx ON intake_audit (intake_id, at);

encore run starts Postgres locally, applies the migration and keeps uploaded objects on local disk, so the whole flow of creating, drafting, uploading and submitting can be driven with curl on a laptop. The object storage docs cover signed URLs and the Pub/Sub docs cover retries and the dead-letter queue.

Deploying follows Connect your cloud account and a push, and RDS or Cloud SQL, the private bucket and the topic are created in your account. Encore provisions an IAM role for the service, or a service account on GCP. An AI coding agent asked to add a new required field edits the submit check and the form in one change and runs the flow locally before review.

Best fit: Healthtech teams that need intake forms with drafts, uploads, an EHR hand-off and an audit trail running as a service in their own AWS or GCP account.

What should you check before going live?

Put authentication in front of every endpoint, since the staff read path above takes the actor as a parameter only to keep the example short and should take it from your auth handler. Encrypt the bucket and the database, set a retention period for abandoned drafts, and send only the fields the EHR needs. Confirm with your compliance team which agreements and controls apply, because the service stores and records the data and does not decide what the rules require.

Frequently asked questions

What should a patient intake backend store?

The form answers, the submission state, a reference to the uploaded insurance card or ID and an audit record of who read or changed the form. Keep the answers in one table with a JSON column, keep images in object storage, and store only the identifiers other systems need.

How do I stop an intake form from being sent to the EHR twice?

Move the form from submitted to synced with a guarded update, and send the intake id as the idempotency key on the EHR call. A redelivered event then finds the form already synced, or the EHR rejects the repeat call, and either way nothing is created twice.

Do intake forms need an audit log under HIPAA?

Yes. The HIPAA Security Rule requires audit controls on systems that contain electronic PHI, which means recording and examining activity such as who opened a record. Writing an audit row in the same transaction as every read and change is the simplest way to make that record complete.

How do I keep PHI in my own AWS account?

Build the backend with Encore, declaring the Postgres database and the upload bucket in code, and deploy it to your own AWS or GCP account. The data lives in RDS and S3 in your account. A Business Associate Addendum with the cloud provider is required to handle PHI there, and it is your responsibility to put that agreement in place and to decide which controls apply.

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders