Upload a file
Add private attachments to the starter's Todos. Upload a PDF or plain-text file, keep its attachment record after a refresh, download it through an authorized route, and remove both the file and its record. Replace a file by uploading and checking the new attachment before removing the old one.
Before you start
Use the Next.js and SQLite app from Quickstart, with sign-in
and Todos working. Run commands from the app root. No Projects tutorial or cloud
storage account is required. This guide uses the generated local storage
provider, which writes under storage/app.
Each upload accepts one file up to 5 MiB. A Todo can have several attachments. Only its owner can upload, list, download, or remove them. Keep ownership immutable, and remove attachments before deleting their Todo.
The database owns attachment records; StoragePort owns file bytes. They do
not share a transaction. The steps below preserve a retry path for failed
removals and explain how to handle uncertain upload completion.
Generate the upload workflow
bun beignet make upload todos.attachment --ui
bun install
bun run formatKeep the generated upload registry, route, storage provider, browser-safe
manifest, and AttachmentUploader. The manifest allows application/pdf or
text/plain, one file per upload, 5 MiB maximum, and private visibility.
If you already have this workflow, keep your registrations and merge the edits below. The diffs target the formatted default SQLite starter after generation. Do not regenerate over customized upload, database, or auth code.
Persist attachment records
Store an immutable object key and display metadata against the Todo. The foreign key prevents deleting a Todo while it still has attachment records; a unique key makes replaying completion harmless to the database record.
70 unmodified lines71727374757677787980818283848586878870 unmodified lines }, (table) => [index("todos_user_idx").on(table.userId, table.createdAt)],);
export const todoAttachments = sqliteTable( "todo_attachments", { id: text("id").primaryKey(), todoId: text("todo_id") .notNull() .references(() => todos.id, { onDelete: "restrict" }), key: text("key").notNull().unique(), fileName: text("file_name").notNull(), size: integer("size").notNull(), createdAt: text("created_at").notNull(), }, (table) => [index("todo_attachments_todo_idx").on(table.todoId)],);44 unmodified lines4546474849505152535455565758596061626364656644 unmodified linesexport type CreateTodoInput = z.infer<typeof CreateTodoInputSchema>;export type ListTodosInput = z.infer<typeof ListTodosInputSchema>;export type UpdateTodoInput = z.infer<typeof UpdateTodoInputSchema>;
export const TodoAttachmentSchema = z.object({ id: z.uuid(), fileName: z.string(), size: z.number().int().nonnegative(), createdAt: z.string().datetime(),});export const TodoAttachmentInputSchema = TodoIdInputSchema.extend({ attachmentId: z.uuid(),});export const ListTodoAttachmentsOutputSchema = z.object({ items: z.array(TodoAttachmentSchema),});export type TodoAttachment = z.infer<typeof TodoAttachmentSchema>;
export const StoredTodoAttachmentSchema = TodoAttachmentSchema.extend({ todoId: z.uuid(), key: z.string(),});2 unmodified lines3456678911 unmodified lines212223242526272829303132333435362 unmodified lines OffsetPageInfo, PageResult,} from "@beignet/core/pagination";import type { Todo } from "@/features/todos/schemas";import type { Todo, TodoAttachment } from "@/features/todos/schemas";
export type ListTodosResult = PageResult<Todo, OffsetPageInfo>;
11 unmodified lines findById(id: string): Promise<Todo | null>; create(input: NewTodo): Promise<Todo>; update(id: string, input: UpdateTodoData): Promise<Todo>; delete(id: string): Promise<boolean>;}
export type StoredTodoAttachment = TodoAttachment & { todoId: string; key: string;};export interface TodoAttachmentRepository { list(todoId: string): Promise<StoredTodoAttachment[]>; findById(id: string): Promise<StoredTodoAttachment | null>; save(attachment: StoredTodoAttachment): Promise<void>; delete(id: string): Promise<void>;}Add the repository adapter. It stores the server-selected key and upload ID;
there is no HTTP endpoint that accepts attachment records or storage keys from
the browser. save leaves an existing key's record unchanged on replay.
// infra/todos/drizzle-todo-attachment-repository.ts
import "@beignet/core/server-only";
import type { DrizzleSqliteDatabase } from "@beignet/provider-db-drizzle/sqlite";
import { asc, eq } from "drizzle-orm";
import type { TodoAttachmentRepository } from "@/features/todos/ports";
import * as schema from "@/infra/db/schema";
export function createTodoAttachmentRepository(
db: DrizzleSqliteDatabase<typeof schema>,
): TodoAttachmentRepository {
return {
list(todoId) {
return db
.select()
.from(schema.todoAttachments)
.where(eq(schema.todoAttachments.todoId, todoId))
.orderBy(asc(schema.todoAttachments.createdAt));
},
async findById(id) {
const [row] = await db
.select()
.from(schema.todoAttachments)
.where(eq(schema.todoAttachments.id, id))
.limit(1);
return row ?? null;
},
async save(attachment) {
await db
.insert(schema.todoAttachments)
.values(attachment)
.onConflictDoNothing({ target: schema.todoAttachments.key });
},
async delete(id) {
await db
.delete(schema.todoAttachments)
.where(eq(schema.todoAttachments.id, id));
},
};
}Wire the repository through the starter's existing database provider and transaction factory. Declaring a deferred port alone does not supply it.
7 unmodified lines891011111213141516171819202122235 unmodified lines293031323334357 unmodified lines UnitOfWorkPort,} from "@beignet/core/ports";import type { AuthorizationContext, todoPolicy } from "@/features/todos/policy";import type { TodoRepository } from "@/features/todos/ports";import type { TodoAttachmentRepository, TodoRepository,} from "@/features/todos/ports";import type { AuthPort } from "./auth";
export type AppTransactionPorts = { idempotency: IdempotencyPort; todos: TodoRepository; todoAttachments: TodoAttachmentRepository;};
export type AppGate = BoundGate<[typeof todoPolicy]>;5 unmodified lines idempotency: IdempotencyPort; logger: LoggerPort; todos: TodoRepository; todoAttachments: TodoAttachmentRepository; uow: UnitOfWorkPort<AppTransactionPorts>; storage: StoragePort;};123453 unmodified lines91011121314import type { DrizzleSqliteDatabase } from "@beignet/provider-db-drizzle/sqlite";import { createTodoAttachmentRepository } from "@/infra/todos/drizzle-todo-attachment-repository";import { createDrizzleTodoRepository } from "@/infra/todos/drizzle-todo-repository";import type { AppTransactionPorts } from "@/ports";import type * as schema from "./schema";3 unmodified lines): Omit<AppTransactionPorts, "idempotency"> { return { todos: createDrizzleTodoRepository(db), todoAttachments: createTodoAttachmentRepository(db), };}25 unmodified lines262728292930313233343525 unmodified lines const repositories = createRepositories(dbPort.drizzle); const idempotency = createDrizzleSqliteIdempotencyPort(dbPort.drizzle);
const providedPorts: Pick<AppPorts, "idempotency" | "todos" | "uow"> = { const providedPorts: Pick< AppPorts, "idempotency" | "todos" | "todoAttachments" | "uow" > = { ...repositories, idempotency, uow: createDrizzleSqliteUnitOfWork({25 unmodified lines262728292930313233343536373825 unmodified lines errorReporter: createNoopErrorReporter(), gate, }, deferred: ["auth", "idempotency", "logger", "todos", "uow", "storage"], deferred: [ "auth", "idempotency", "logger", "todoAttachments", "todos", "uow", "storage", ],});Generate and review the migration before applying it:
bun beignet db generate
bun beignet db migrate
bun beignet db statusKeep the generated SQL and metadata under drizzle/ in version control. This adds
a table; it does not reset existing Todos or files. If an earlier uploader already
stored files, they need an explicit, reviewed backfill before this screen can list
them. Never infer ownership from a filename or a browser-supplied object key.
Define access and deletion errors
Use the Todos policy for attachment ownership and the app error catalog for missing files and blocked Todo deletion.
12345678910111213141516import { createAppError, defineErrors } from "@beignet/core/errors";
export const errors = defineErrors({ AttachmentNotFound: { code: "ATTACHMENT_NOT_FOUND", status: 404, message: "Attachment not found", }, TodoHasAttachments: { code: "TODO_HAS_ATTACHMENTS", status: 409, message: "Remove this Todo's attachments before deleting it", }, Unauthorized: { code: "UNAUTHORIZED", status: 401,9 unmodified lines101112131314151611 unmodified lines28293031323334359 unmodified linesfunction authorizeOwner( ctx: AuthorizationContext, todo: Todo, action: "update" | "delete", action: "update" | "delete" | "manage attachments for",) { if (ctx.actor.type !== "user") { return deny(`You must be signed in to ${action} todos.`);11 unmodified lines}
export const todoPolicy = definePolicy({ "todos.attachments.manage": (ctx: AuthorizationContext, todo: Todo) => authorizeOwner(ctx, todo, "manage attachments for"), "todos.create": (ctx: AuthorizationContext) => { if (ctx.actor.type === "user") return true; return deny("You must be signed in to create todos.");Guard Todo deletion in its repository with a single conditional SQL delete. Its boolean result tells the use case whether a row was removed; update the memory test helper to return the same result. The foreign key also rejects an attachment insert whose parent has already been deleted; it does not cascade away the only record of a stored file.
1234456772 unmodified lines80818283838485868788899091929394import "@beignet/core/server-only";import { offsetPageResult } from "@beignet/core/pagination";import type { DrizzleSqliteDatabase } from "@beignet/provider-db-drizzle/sqlite";import { count, desc, eq } from "drizzle-orm";import { and, count, desc, eq, notExists } from "drizzle-orm";import type { NewTodo, TodoRepository,72 unmodified lines return toTodo(row); }, async delete(id: string) { await db.delete(schema.todos).where(eq(schema.todos.id, id)); const attachments = db .select({ id: schema.todoAttachments.id }) .from(schema.todoAttachments) .where(eq(schema.todoAttachments.todoId, id)); const [deleted] = await db .delete(schema.todos) .where(and(eq(schema.todos.id, id), notExists(attachments))) .returning({ id: schema.todos.id }); return !!deleted; }, };}46 unmodified lines474849505051525346 unmodified lines return next; }, async delete(id: string) { todos.delete(id); return todos.delete(id); }, };}Define the attachment API
Add list, download, and remove contracts. Each URL contains both the Todo ID and attachment ID. The list returns display metadata, not storage keys. The download contract uses a native binary response, described explicitly in OpenAPI.
6 unmodified lines789101112131453 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051066 unmodified linesimport { errors } from "@/features/shared/errors";import { CreateTodoInputSchema, TodoAttachmentInputSchema, ListTodoAttachmentsOutputSchema, ListTodosInputSchema, ListTodosOutputSchema, TodoIdInputSchema,53 unmodified lines .pathParams(TodoIdInputSchema) .errors({ Forbidden: errors.Forbidden, TodoHasAttachments: errors.TodoHasAttachments, TodoNotFound: errors.TodoNotFound, }) .responses({ 204: null, });
const attachments = todos.errors({ Forbidden: errors.Forbidden, TodoNotFound: errors.TodoNotFound, AttachmentNotFound: errors.AttachmentNotFound,});export const listTodoAttachments = attachments .get("/api/todos/:id/attachments") .pathParams(TodoIdInputSchema) .responses({ 200: ListTodoAttachmentsOutputSchema });export const downloadTodoAttachment = attachments .get("/api/todos/:id/attachments/:attachmentId/download") .pathParams(TodoAttachmentInputSchema) .responses({ 200: null }) .openapi({ responses: { "200": { description: "Private attachment bytes", content: { "application/octet-stream": { schema: { type: "string", format: "binary" }, }, }, }, }, });export const removeTodoAttachment = attachments .delete("/api/todos/:id/attachments/:attachmentId") .pathParams(TodoAttachmentInputSchema) .responses({ 204: null });Add the use cases to the starter's existing use-cases.ts. Resolve the Todo and
authorize it before looking up an attachment. Verify that the attachment belongs
to that Todo, even if the same user owns both resources.
For removal, delete the object first. If storage throws, keep the record so the
caller can retry. If the object is already missing, its delete result is
false; continue removing the record. A database failure after object removal
therefore remains retryable.
2 unmodified lines34567891011122 unmodified lines1516171819202124 unmodified lines46474844495051525329 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251262 unmodified linesimport { useCase } from "@/lib/use-case";import { CreateTodoInputSchema, TodoAttachmentSchema, StoredTodoAttachmentSchema, TodoAttachmentInputSchema, ListTodoAttachmentsOutputSchema, TodoSchema, DeleteTodoOutputSchema, TodoIdInputSchema,2 unmodified lines UpdateTodoInputSchema,} from "./schemas";import { appError } from "@/features/shared/errors";import type { AppContext } from "@/app-context";import { normalizeOffsetPage } from "@beignet/core/pagination";
export const createTodoUseCase = useCase24 unmodified lines
await ctx.gate.authorize("todos.delete", todo);
await tx.todos.delete(input.id); if (!(await tx.todos.delete(input.id))) throw appError("TodoHasAttachments"); }); });
29 unmodified lines return tx.todos.update(input.id, { completed: input.completed }); }); });
export async function authorizeTodoAttachments(ctx: AppContext, id: string) { requireUser(ctx); const todo = await ctx.ports.todos.findById(id); if (!todo) throw appError("TodoNotFound"); await ctx.gate.authorize("todos.attachments.manage", todo);}
export const listTodoAttachmentsUseCase = useCase .query("todos.attachments.list") .input(TodoIdInputSchema) .output(ListTodoAttachmentsOutputSchema) .run(async ({ ctx, input }) => { await authorizeTodoAttachments(ctx, input.id); const rows = await ctx.ports.todoAttachments.list(input.id); return { items: rows.map((row) => TodoAttachmentSchema.parse(row)) }; });
export const getTodoAttachmentUseCase = useCase .query("todos.attachments.get") .input(TodoAttachmentInputSchema) .output(StoredTodoAttachmentSchema) .run(async ({ ctx, input }) => { await authorizeTodoAttachments(ctx, input.id); const attachment = await ctx.ports.todoAttachments.findById( input.attachmentId, ); if (!attachment || attachment.todoId !== input.id) throw appError("AttachmentNotFound"); return attachment; });
export const removeTodoAttachmentUseCase = useCase .command("todos.attachments.remove") .input(TodoAttachmentInputSchema) .output(DeleteTodoOutputSchema) .run(async ({ ctx, input }) => { const attachment = await getTodoAttachmentUseCase.run({ ctx, input }); await ctx.ports.storage.delete(attachment.key); await ctx.ports.todoAttachments.delete(attachment.id); });Register the contracts in the existing route group. The download handler passes
only an authorized record's key to createStorageDownloadResponse. It streams
an attachment with Cache-Control: private, no-store and nosniff; a missing
object becomes the catalog's 404 response.
1234567891011121314151617181920212 unmodified lines242526272829303132333435363738394041424344454647import "@beignet/core/server-only";import { createStorageDownloadResponse } from "@beignet/next";import { appError } from "@/features/shared/errors";import { defineRouteGroup } from "@/lib/routes";import { createTodo, listTodoAttachments, downloadTodoAttachment, removeTodoAttachment, deleteTodo, listTodos, updateTodo,} from "@/features/todos/contracts";import { createTodoUseCase, listTodoAttachmentsUseCase, getTodoAttachmentUseCase, removeTodoAttachmentUseCase, deleteTodoUseCase, listTodosUseCase, updateTodoUseCase,2 unmodified linesexport const todoRoutes = defineRouteGroup({ name: "todos", routes: [ { contract: listTodoAttachments, useCase: listTodoAttachmentsUseCase }, { contract: removeTodoAttachment, useCase: removeTodoAttachmentUseCase }, { contract: downloadTodoAttachment, handle: async ({ ctx, path }) => { const attachment = await getTodoAttachmentUseCase.run({ ctx, input: path, }); const response = await createStorageDownloadResponse({ storage: ctx.ports.storage, key: attachment.key, fileName: attachment.fileName, }); if (!response) throw appError("AttachmentNotFound"); return response; }, }, { contract: listTodos, useCase: listTodosUseCase }, { contract: createTodo, useCase: createTodoUseCase }, { contract: updateTodo, useCase: updateTodoUseCase },Save the completed upload
Replace the generated upload definition. Authorization happens before storage and again at completion, since the Todo may have disappeared while bytes were being written. The object key uses a generated upload ID, never the filename. Normalize the filename before using it in a download header.
// features/todos/uploads/attachment.ts
import { z } from "zod";
import { defineUpload } from "@/lib/uploads";
import { attachmentUploadFile } from "../attachment-upload-manifest";
import { authorizeTodoAttachments } from "../use-cases";
export const AttachmentUploadMetadataSchema = z.object({
resourceId: z.uuid(),
});
export type AttachmentUploadMetadata = z.infer<
typeof AttachmentUploadMetadataSchema
>;
export const AttachmentUpload = defineUpload("todos.attachment", {
metadata: AttachmentUploadMetadataSchema,
file: attachmentUploadFile,
async authorize({ ctx, metadata }) {
if (ctx.actor.type !== "user") return false;
const todo = await ctx.ports.todos.findById(metadata.resourceId);
return todo ? ctx.gate.can("todos.attachments.manage", todo) : false;
},
key({ metadata, uploadId }) {
return `todos/${metadata.resourceId}/${uploadId}`;
},
storageMetadata({ metadata }) {
return { resourceId: metadata.resourceId };
},
async onComplete({ ctx, metadata, files }) {
const file = files[0];
if (!file) throw new Error("The upload contained no file");
try {
await authorizeTodoAttachments(ctx, metadata.resourceId);
const fileName = file.name
.replace(/[/\\\p{Cc}]/gu, "_")
.trim()
.slice(0, 180)
.toWellFormed();
await ctx.ports.todoAttachments.save({
id: file.uploadId,
todoId: metadata.resourceId,
key: file.key,
fileName:
!fileName || fileName === "." || fileName === ".."
? "attachment"
: fileName,
size: file.object.size,
createdAt: new Date().toISOString(),
});
} catch (error) {
ctx.ports.logger.error(
"Attachment registration failed; reconcile the stored object",
{ key: file.key, todoId: metadata.resourceId },
);
throw error;
}
return { objectKeys: [file.key] };
},
});The result keeps { objectKeys }, as expected by the generated uploader.
onComplete saves only after the file exists. It logs the key if registration
fails but does not blindly delete the object: the database might have committed
before the failure reached the caller. See Handle partial failures
below for recovery.
Show and refresh attachments
Add a component that reuses the generated uploader and the app's existing React
Query client. Upload completion refreshes the attachment list. Removal uses
mutationOptions({ invalidates }), so pending controls include its refresh.
Download links point to the authenticated route rather than a public object URL.
// features/todos/components/todo-attachments.tsx
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { rq } from "@/client";
import { Button } from "@/components/ui/button";
import { listTodoAttachments, removeTodoAttachment } from "../contracts";
import { AttachmentUploader } from "./attachment-uploader";
export function TodoAttachments({ todoId }: { todoId: string }) {
const queryClient = useQueryClient();
const attachments = useQuery(
rq(listTodoAttachments).queryOptions({ path: { id: todoId } }),
);
const remove = useMutation(
rq(removeTodoAttachment).mutationOptions({
invalidates: () => [rq(listTodoAttachments).contractFilter()],
}),
);
return (
<section
aria-label="Todo attachments"
className="w-full space-y-3 border-t pt-3"
>
<AttachmentUploader
resourceId={todoId}
onComplete={() => rq(listTodoAttachments).invalidate(queryClient)}
/>
{attachments.isPending && <p role="status">Loading attachments…</p>}
{attachments.isError && (
<p role="alert">
Could not refresh attachments. Reload the list before uploading again.
</p>
)}
<Button
type="button"
size="sm"
variant="outline"
disabled={attachments.isFetching}
onClick={() => void attachments.refetch()}
>
Refresh attachments
</Button>
{attachments.data?.items.length === 0 && <p>No attachments yet.</p>}
<ul className="space-y-2">
{attachments.data?.items.map((attachment) => (
<li key={attachment.id} className="flex flex-wrap items-center gap-3">
<a
className="min-w-0 break-all underline"
href={`/api/todos/${encodeURIComponent(todoId)}/attachments/${encodeURIComponent(attachment.id)}/download`}
>
{attachment.fileName}
</a>
<span>{attachment.size} bytes</span>
<Button
type="button"
size="sm"
variant="outline"
disabled={remove.isPending}
onClick={() =>
remove.mutate({
path: { id: todoId, attachmentId: attachment.id },
})
}
>
Remove<span className="sr-only"> {attachment.fileName}</span>
</Button>
</li>
))}
</ul>
{remove.isError && (
<p role="alert">
Could not remove the attachment. Refresh the list and retry removal if
it remains.
</p>
)}
</section>
);
}Render it below each Todo's controls and display errors from the Todo delete action, including the instruction to remove attachments first. Give the generated picker vertical spacing and a file input that fits narrow screens.
16 unmodified lines1718192021222360 unmodified lines84858687888990919211 unmodified lines10410510610310710810911011111211326 unmodified lines14014114214314414514616 unmodified lines updateTodo,} from "@/features/todos/contracts";import { cn } from "@/lib/utils";import { TodoAttachments } from "./todo-attachments";
const createTodoForm = rhf(createTodo);
60 unmodified lines ) : null} </form>
{deleteTodoMutation.isError && ( <p role="alert">{deleteTodoMutation.error.message}</p> )} <Card className="py-0"> <CardContent className="px-0"> {todosQuery.isPending ? (11 unmodified lines ) : ( <ul className="divide-y"> {todos.map((todo) => ( <li key={todo.id} className="flex items-center gap-3 px-4 py-3"> <li key={todo.id} className="flex flex-wrap items-center gap-3 px-4 py-3" > <Checkbox id={`todo-${todo.id}`} checked={todo.completed}26 unmodified lines > <Trash2Icon /> </Button> <TodoAttachments todoId={todo.id} /> </li> ))} </ul>24 unmodified lines2526272829282930313233343536373824 unmodified lines : undefined;
return ( <section className="attachment-uploader"> <label htmlFor={inputId}>Attachment</label> <section className="attachment-uploader space-y-2"> <label className="block text-sm font-medium" htmlFor={inputId}> Attachment </label> <input id={inputId} type="file" className="block w-full min-w-0 text-sm file:mr-3 file:rounded-md file:border file:px-3 file:py-1" accept={upload.accept} disabled={disabled || upload.isUploading} onChange={(event) => {The generated picker reports upload progress, cancellation, errors, and Upload complete. Local uploads use the server transport, so progress may jump from 0 to 100 rather than advancing smoothly. Reset upload clears picker state; it does not remove an attachment or undo a completed upload.
A failed list refresh does not mean the upload failed. Use Refresh attachments before choosing the same file again. For account-switch cache and form cleanup, follow Connect forms and lists.
Test ownership and retryable removal
Add a focused test using the real Todos policy, the starter's repository helper, and memory storage. It rejects another account before creating a record, checks private visibility and file limits, and proves a failed storage delete leaves the record available for retry.
// features/todos/tests/attachments.test.ts
import { createMemoryStorage, createUserActor } from "@beignet/core/ports";
import { createTestContext } from "@beignet/core/testing";
import { createUploadRouter, uploadsFromRegistry } from "@beignet/core/uploads";
import type { AppContext } from "@/app-context";
import { initialPorts } from "@/infra/port-wiring";
import { expect, test } from "@/lib/beignet-test";
import type { StoredTodoAttachment, TodoAttachmentRepository } from "../ports";
import { todoUploads } from "../uploads";
import {
getTodoAttachmentUseCase,
removeTodoAttachmentUseCase,
} from "../use-cases";
import { createTestTodoRepository } from "./helpers";
test("attachments enforce ownership and retain a retry path when storage fails", async () => {
const todos = createTestTodoRepository();
const todo = await todos.create({ userId: "owner", title: "Attach a note" });
const rows = new Map<string, StoredTodoAttachment>();
const todoAttachments: TodoAttachmentRepository = {
async list(todoId) {
return [...rows.values()].filter((row) => row.todoId === todoId);
},
async findById(id) {
return rows.get(id) ?? null;
},
async save(row) {
if (!rows.has(row.id)) rows.set(row.id, row);
},
async delete(id) {
rows.delete(id);
},
};
const memory = createMemoryStorage();
let failDelete = false;
const storage = {
...memory,
async delete(key: string) {
if (failDelete) throw new Error("Storage unavailable");
return memory.delete(key);
},
};
const contextFor = (id: string) =>
createTestContext<AppContext>()({
actor: createUserActor(id),
auth: {
user: { id, name: id, email: `${id}@example.com` },
session: { id: `session_${id}` },
},
ports: { todos, todoAttachments, storage, gate: initialPorts.gate },
ambient: false,
});
const owner = contextFor("owner");
const other = contextFor("other");
const routerFor = (ctx: AppContext) =>
createUploadRouter({
uploads: uploadsFromRegistry(todoUploads),
ctx,
storage,
});
const formData = new FormData();
formData.set("metadata", JSON.stringify({ resourceId: todo.id }));
formData.append(
"file",
new File(["hello"], "note.txt", { type: "text/plain" }),
);
try {
await expect(
routerFor(other.ctx).upload("todos.attachment", { formData }),
).rejects.toMatchObject({ code: "UNAUTHORIZED_UPLOAD" });
expect(rows.size).toBe(0);
const result = await routerFor(owner.ctx).upload("todos.attachment", {
formData,
});
const record = [...rows.values()][0];
if (!record) throw new Error("Expected an attachment record");
expect(result.result).toEqual({ objectKeys: [record.key] });
expect((await storage.stat(record.key))?.visibility).toBe("private");
const input = { id: todo.id, attachmentId: record.id };
for (const useCase of [
getTodoAttachmentUseCase,
removeTodoAttachmentUseCase,
]) {
await expect(
useCase.run({ ctx: other.ctx, input }),
).rejects.toMatchObject({ code: "FORBIDDEN" });
}
failDelete = true;
await expect(
removeTodoAttachmentUseCase.run({ ctx: owner.ctx, input }),
).rejects.toThrow("Storage unavailable");
expect(rows.size).toBe(1);
expect(await storage.exists(record.key)).toBe(true);
failDelete = false;
await removeTodoAttachmentUseCase.run({ ctx: owner.ctx, input });
expect(rows.size).toBe(0);
expect(await storage.exists(record.key)).toBe(false);
for (const file of [
{ name: "image.png", contentType: "image/png", size: 5 },
{
name: "large.txt",
contentType: "text/plain",
size: 5 * 1024 * 1024 + 1,
},
]) {
await expect(
routerFor(owner.ctx).prepare("todos.attachment", {
metadata: { resourceId: todo.id },
files: [file],
}),
).rejects.toMatchObject({ code: "INVALID_UPLOAD_FILE" });
}
} finally {
await owner.dispose();
await other.dispose();
}
});bun run format
bun run test
bun beignet check
bun run devUse Test a feature to add HTTP and database tests for
this app's complete configuration. Include the real schema and migrations: a
memory repository cannot prove a foreign key, unique constraint, or conditional
SQL deletion. Assert 401 for anonymous list/download/delete, 403 for another
account, and 404 for an attachment ID paired with the wrong Todo.
Try the complete flow
- Sign in, create a Todo, and select a small
.txtfile. Expect Upload complete. and a download link. Refresh the page and confirm the link remains. - Download it. Expect the original bytes, an attachment filename, and
Cache-Control: private, no-storein the response. Copy the URL into a signed-out session and a second account; neither should receive the bytes. - Try an image or a file over 5 MiB. Expect a validation error without a new attachment. The server enforces the manifest independently of the picker.
- Replace the file by uploading its replacement, opening that new download, and then removing the old attachment. Both remain visible until removal succeeds; a rejected replacement leaves the original available.
- Press Delete todo while an attachment remains. Expect the instruction to remove its attachments first. Remove them, verify their links no longer work, and then delete the Todo.
- In a test, make storage deletion throw. Confirm the record and bytes remain.
Then make database deletion throw after storage succeeds: the record remains,
downloads return
404, and retrying removal clears the record.
Handle partial failures
Database writes and object-storage writes are separate operations. Use these observable states to decide what to retry:
| State | Recovery |
|---|---|
| Upload rejected before completion | Fix the file or access issue. The multipart router attempts cleanup of rejected files; investigate any cleanup-failure event. |
| Upload failed or was cancelled after bytes were sent | Refresh attachments first. A disconnected browser does not prove the server stopped, and retrying the upload can create another attachment. |
| Registration failed | Find the logged object key and check the database. Preserve an object with a committed record; it may be a lost response after success. |
| Storage removal failed | Keep the record and retry removal after storage recovers. |
| Bytes removed but record deletion failed | Download returns 404. Retry removal; an already-missing object is acceptable. |
Todo deletion returns 409 | Remove its attachments, then retry. Never delete the records alone to bypass the guard. |
For an unreferenced object, reconcile after in-flight uploads and completion attempts have settled. Verify against the authoritative database that no record references the exact key before removing it through your storage provider's operator tooling. Retain keys from failed completion and cleanup logs so they can be investigated. This guide does not install automatic orphan cleanup.
For unattended recovery, design a durable upload-intent or cleanup record and a retrying job or outbox workflow. Do not make a best-effort callback responsible for required deletion. Test process crashes, duplicate completion, and concurrent deletion before enabling automated cleanup. Account deletion and bulk maintenance need the same attachment-removal policy; a SQL cascade cannot delete file bytes.
Deploy with durable storage
Local storage needs persistent disk shared by every process that serves files. Use a hosted storage provider on serverless hosts such as Vercel, and review the host's request-size limit. The 5 MiB application limit does not raise that platform limit. Use direct uploads when the provider and file sizes require them.
The guide's download route works through StoragePort after a provider swap.
Temporary URLs are an alternative for supported providers, but authorize the
record first and treat the URL as a reusable bearer credential until expiry.
Keep storage outside public/static directories and retain private visibility.
The MIME allowlist is not a malware scan. Add file verification or quarantine appropriate to the files your application accepts. Preserve record ownership, cleanup rules, and download authorization when extending this workflow.
Work with your agent
Read https://beignetjs.com/markdown/agent-instructions.md and the app's local
instructions. Follow https://beignetjs.com/markdown/guides/upload-file.md.
Inspect existing uploads, storage, auth, Todos policies, repositories, and migrations.
Keep generated registrations and custom behavior. Persist private attachment records
using server-selected keys. Authorize upload, list, download, and removal against
the saved Todo, and verify each attachment belongs to that Todo. Stream downloads
through the authorized route. Remove bytes before records, keep failed removal
retryable, and block Todo deletion while attachments remain.
Test owner and other-account behavior, anonymous requests, wrong Todo/attachment
pairs, persistence after reload, private download headers, MIME and size limits,
completion replay, and failures on either side of deletion. Verify uncertain
completion never deletes a committed file. Run format, migrations, tests, and
beignet check. Report changed files, results, skipped checks, and the orphan-cleanup
and deployment decisions that remain application-owned.