Short answer: treat the Next.js server action as a short-lived authorization decision, not as the file pipe. Let the browser upload the receipt directly to private object storage, then make a separate completion check before any parser or reviewer can use the original. That design keeps the audit boundary visible: the action decides who may write, storage holds the bytes, and the database records what was actually accepted.
For a healthtech receipt workflow, delivery simplicity is tempting. A browser posts a file, the server saves it, and an OCR or LLM job starts. The failure is subtle: a successful authorization request is not proof that the bytes arrived, and a successful parse is not proof that the original can be retrieved later. My decision axis is reliability under audit, not the shortest demo.
The failure usually appears later.
Imagine an auditor opening claim claim-1842 after a busy week. The database says the receipt was parsed, but the browser closed after receiving its upload grant; a queue retry saw the pending row and treated the object key as if it were an accepted file. In a different run, the bytes arrived but completion was called twice, producing two processing jobs with different derived totals. In a third, the reviewer still had a signed read from before their access changed. None of these cases is fixed by making the upload button prettier. They require separate write authorization, object acceptance, processing eligibility, and read authorization, each tied to the same receipt id and each visible in an audit record. That is the boundary I would review before measuring latency or storage cost.
I've learned to ask one unfashionable question early: what exact event lets us say "this original is preserved"? Until that answer is recorded, the receipt is an upload attempt.
Receipt Upload Reliability: The Acceptance Event
A receipt row should exist before the browser sends bytes. Give it a server-generated object key, an owning user or claim, declared content type, declared byte count, and a state such as pending, ready, or expired. Store the display filename as metadata. Do not use an untrusted filename as the object path; slashes, control characters, and duplicate names turn a friendly field into an awkward authorization surface.
The state machine makes the workflow testable:
type ReceiptState = "pending" | "ready" | "expired"; type Receipt = { id: string; claimId: string; ownerId: string; objectKey: string; contentType: string; declaredBytes: number; state: ReceiptState; }; function canParse(receipt: Receipt): boolean { return receipt.state === "ready"; } pending means permission was issued and work may still be incomplete. ready means the application has checked the expected object and accepted the transition. expired means the session was abandoned or aged out and must not enter the parser queue. This is a small distinction with a large payoff: a worker never has to infer business truth from the presence of a URL.
The original file is evidence. Extracted merchant names, totals, and model output are derived records. Keep the source object immutable for the audit path, and record the object key plus an integrity value with each processing job. If a model run needs to be repeated, it should read the same accepted source rather than replacing it with a newly rendered preview.
Healthtech Audit Governance: What the Original Must Retain
The action should do four things in order: authenticate the caller, authorize the claim, create the pending row, and return an exact upload grant. The grant contains the method, URL, and required headers produced by the storage adapter. The browser uses those values as returned. It does not construct a provider-specific request or receive the credential that created the grant.
The application-facing function can stay deliberately boring. Its name is an application contract, not a claim about a framework route or storage provider:
type UploadGrant = { receiptId: string; objectKey: string; request: { method: "PUT" | "POST"; url: string; headers: Record<string, string>; }; }; async function requestReceiptGrant(input: { claimId: string; filename: string; contentType: string; bytes: number; }): Promise<UploadGrant> { // The server action authenticates and authorizes before this boundary. return createPendingReceiptAndGrant(input); } The important behavior is behind createPendingReceiptAndGrant: generate a random key, persist the ownership relation, constrain the expected metadata, and ask the storage adapter for a short-lived write. A declared application/pdf value helps routing, but it is not a forensic proof of the bytes. Validate the content before parsing.
The browser's job is intentionally narrow: request permission, send bytes, and ask the application to confirm completion. It should surface failures instead of treating a closed tab as success.
export async function uploadReceipt(file: File, claimId: string): Promise<string> { const grant = await requestReceiptGrant({ claimId, filename: file.name, contentType: file.type || "application/octet-stream", bytes: file.size, }); const upload = await fetch(grant.request.url, { method: grant.request.method, headers: grant.request.headers, body: file, }); if (!upload.ok) { throw new Error(`Direct upload failed: HTTP ${upload.status}`); } await confirmReceiptUpload(grant.receiptId); return grant.receiptId; } The completion action must look up the pending row for the authenticated user, verify the expected key and object metadata, and transition the row idempotently. Calling completion twice should leave one ready receipt. Calling it for another user's row should not. The parser consumes ready rows only.
How can a Next.js server action implement private browser uploads?
The happy path proves almost nothing. I would test authorization and interruption as separate dimensions: a user requesting a grant for another claim, a revoked reviewer requesting a read, a tab closed after grant creation, a direct request interrupted halfway through, a completion for a missing object, and two completion calls racing each other. Each test needs a state outcome and an audit event. A swallowed exception is not an outcome.
Use a matrix like this in integration tests:
| Event | Required result | What to observe |
|---|---|---|
| Grant for unauthorized claim | No pending row or usable grant | Authorization decision |
| Browser stops before upload | Row remains pending until expiry | Cleanup classification |
| Upload finishes, completion repeats | One ready row | Idempotent transition |
| Permission revoked before read | No signed read is issued | Read audit event |
| Bytes fail content validation | Original remains quarantined | Validation reason |
The retry policy belongs at the state boundary. Retrying the same completion is safe when the operation is idempotent; silently creating a second grant for the same receipt may not be. A new receipt should get a new key, so a retry cannot overwrite an original that an auditor may already reference.
For private delivery, authorize again when a reviewer asks to view the receipt, then issue a short-lived signed read. An old upload grant must not become a permanent download link. Access changes: a claim can move teams, a reviewer can lose access, and retention can expire the record. The delivery response should also set presentation metadata deliberately; Content-Disposition describes how a response is presented to a user, which is separate from the object key itself.
Keep observability split into useful signals. Log the receipt id, state transition, actor, and object key reference for audit. Track upload duration, size distribution, retries, and parser latency for operations. Keep model token telemetry separate, so an expensive inference run does not hide a broken file lifecycle. Three words: preserve the source.
Storage Boundary Migration: Portability and Retention
Direct browser delivery is a protocol pattern, not a recommendation for a particular provider. The right boundary depends on retention controls, deployment location, account ownership, and how much provider-specific behavior the team will test. An S3-compatible label does not by itself prove identical support for signed reads, metadata, versioning, conditional writes, or lifecycle rules.
| Boundary | Useful when | Cost of ownership |
|---|---|---|
| Direct object-storage adapter | One backend already matches deployment and retention needs | The application owns its credentials and adapter details |
| Compatibility layer | Several backends should share one application contract | The layer adds another authorization and observability boundary |
| Self-hosted object storage | Data placement and operational control matter most | The team owns durability, backups, upgrades, and incident response |
| Database-backed blobs | Files are small and transaction coupling matters most | Database growth, backup size, and delivery performance become central |
The catch is that direct object delivery is not suitable when every byte must pass through an application transaction before storage, or when the chosen adapter cannot demonstrate the retention and access controls required by the healthtech workflow. Stick with a server-mediated path when that policy is non-negotiable.
For a solo founder shipping AI features, reducing adapter code can be valuable, but it is not a reliability argument by itself. Measure receipt sizes, interrupted uploads, completion retries, audit-read latency, and cleanup volume before choosing. I'm not sure multipart transfer is justified for a given product until those measurements show ordinary single-request uploads are the constraint; multipart adds another lifecycle that must be cancelled and cleaned up.
The design is ready when the team can answer three questions without opening storage logs: who authorized the write, which bytes were accepted as the original, and who authorized the later read? If those answers live in different systems with no shared receipt id, the architecture is easy to ship and hard to defend.
References
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Disposition
- https://aws.amazon.com/s3/pricing/
Further reading
- MDN, Content-Disposition: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Disposition
- Amazon S3 pricing concepts: https://aws.amazon.com/s3/pricing/

