Skip to content

Creating your first resource

rocambille edited this page Nov 1, 2026 · 20 revisions

Summary: This guide explains how to create a complete full-stack resource (from database tables and Express API endpoints to React CRUD user interfaces), featuring both an immediate post-clone checklist and an end-to-end tutorial.

What you'll learn:

  • Understand the full-stack resource lifecycle in StartER
  • Follow the 7-step post-clone checklist to rapidly scaffold new features
  • Build a database table in SQLite with schema and seeder definitions
  • Build a modular Express API with routing, an authentication wall, and repository queries
  • Create accessible, Zod-validated React CRUD components
  • Verify end-to-end functionality using tests and contracts

Tip

If you already understand the StartER architecture and just used npm run make:clone, jump directly to Track 1: The complete post-clone checklist for the 7-step integration guide.

Overview: The full-stack resource lifecycle

In StartER, a resource represents a cohesive business entity (such as an item, user, post...). Creating a resource spans four synchronized layers:

┌────────────────┐     ┌────────────────┐     ┌────────────────┐     ┌────────────────┐
│   1. Database  │ ──> │ 2. Express API │ ──> │ 3. React Views │ ──> │ 4. Verification│
│  (schema.sql)  │     │ (routes/repo)  │     │  (CRUD forms)  │     │  (contracts)   │
└────────────────┘     └────────────────┘     └────────────────┘     └────────────────┘

You can build a resource by following the Track 1 checklist (via CLI scaffolding) or the Track 2 tutorial (from scratch).

Track 1: The complete post-clone checklist

When you clone an existing module to scaffold a new resource (e.g. cloning item to post), follow this complete checklist to ensure every layer is wired correctly:

# 1. Scaffold backend module & frontend components
npm run make:clone -- src/express/modules/item src/express/modules/post Item Post
npm run make:clone -- src/react/components/item src/react/components/post Item Post
  1. Database schema:
    • Add the CREATE TABLE definition to src/database/schema.sql (and optionally sample development data to src/database/seeder.sql).
    • Run npm run database:reset to apply the changes to your local database.
  2. Zod schemas & TypeScript types:
    • Adjust the entity schema (e.g. PostSchema and its inferred type Post = z.infer<typeof PostSchema>) in src/express/modules/post/postSchemas.ts.
    • Expose the global ambient type in src/types/index.d.ts (type Post = import("../express/modules/post/postSchemas").Post;).
  3. Express routes registration:
    • In src/express/routes.ts, import your new router (import postRoutes from "./modules/post/postRoutes";) and mount it with router.use(postRoutes);.
  4. Backend logic & validation:
    • In src/express/modules/post/postRoutes.ts, verify the authentication wall (router.use(BASE_PATH, authActions.verifyAccessToken)): ensure public routes are placed above the wall and protected routes below it.
    • In postValidators.ts, adjust the validation middleware to match your updated schemas.
    • In postRepository.ts, adjust SQL queries and column projections.
  5. React routes registration:
    • In src/react/routes.tsx, import your new route array (import { postRoutes } from "./components/post";) and spread it into the main routes array (...postRoutes,).
  6. React UI & forms:
    • In PostForm.tsx, adjust input fields, labels, accessibility attributes (aria-describedby, htmlFor), and client-side Zod validation schema.
    • In PostList.tsx, PostShow.tsx, PostCreate.tsx, and PostEdit.tsx, adjust rendered fields and API endpoints as needed.
  7. Verification & contracts:
    • Run npm run types:check to ensure there are no TypeScript errors.
    • Run npm run biome:check (or npm run biome:fix) to ensure formatting standards.
    • If using contract testing, add your resource fixtures in tests/fixtures/posts.ts, register seedPosts in tests/fixtures/index.ts, and define contract cases in tests/contracts/posts.ts.
    • Run npm run test to verify contracts and application integrity.

Track 2: Step-by-step tutorial (building from scratch)

Step 1: The database with SQLite

In our Zero-Config architecture with SQLite, adding a resource starts with defining its table.

  1. Schema update: Open src/database/schema.sql and add the CREATE TABLE declaration. Something like this:
    create table item (
      id integer primary key not null,
      title varchar(255) not null,
      created_at datetime default (strftime('%Y-%m-%dT%H:%M:%SZ')),
      deleted_at datetime default null,
      user_id integer not null,
      foreign key(user_id) references user(id) on delete cascade
    );
  2. Development seed data (optional): Add initial test rows to src/database/seeder.sql for your local development database.
  3. Reset local database: Run the reset script to recreate your local database.sqlite file:
    npm run database:reset

Tip

🤖 AI shortcut: Instead of writing SQL manually, ask your AI agent: "Create a CREATE TABLE statement for a task resource with title, description, and user_id. Add it to schema.sql and run npm run database:reset."

Caution

npm run database:reset erases and recreates your local SQLite file. In production environments, use versioned migrations instead (see Database migrations).

Step 2: The backend with Express

StartER structures the Express backend with a modular architecture, grouping all related files inside src/express/modules/<resource>/:

src/express
├── routes.ts
└── modules
    └── item
        ├── itemActions.ts        # Request handlers (HTTP status & response shaping)
        ├── itemParamConverter.ts # Automatic ID-to-entity resolution
        ├── itemRepository.ts     # SQL queries & database operations
        ├── itemRoutes.ts         # Module route definitions & auth wall
        ├── itemSchemas.ts        # Zod schemas and inferred TypeScript types
        └── itemValidators.ts     # Input validation middleware

1. Schemas and shared type

The module starts with itemSchemas.ts, its single source of truth: ItemSchema parses database rows, and ItemDTOSchema, derived from it, validates client input:

// src/express/modules/item/itemSchemas.ts
import { z } from "zod";

export const ItemSchema = z.object({
  id: z.number(),
  title: z.string().max(255),
  user_id: z.number(),
});

export type Item = z.infer<typeof ItemSchema>;

export const ItemDTOSchema = ItemSchema.omit({
  id: true,
  user_id: true,
});

export type ItemDTO = z.infer<typeof ItemDTOSchema>;

export type ItemDTOWithUserId = ItemDTO & {
  user_id: User["id"];
};

Declare the ambient Item type in src/types/index.d.ts, so that Express and React can both use it:

// src/types/index.d.ts
type Item = import("../express/modules/item/itemSchemas").Item;

2. Repository queries

The repository holds all the SQL of the resource. Read queries ignore soft-deleted rows and parse results through ItemSchema:

// src/express/modules/item/itemRepository.ts
import database from "../../../database";
import { type ItemDTOWithUserId, ItemSchema } from "./itemSchemas";

class ItemRepository {
  create(item: ItemDTOWithUserId): Item["id"] {
    const result = database
      .prepare("insert into item (title, user_id) values (?, ?)")
      .run(item.title, item.user_id);

    return Number(result.lastInsertRowid);
  }

  find(id: Item["id"]): Item | null {
    const row = database
      .prepare(
        "select id, title, user_id from item where id = ? and deleted_at is null",
      )
      .get(id);

    return row ? ItemSchema.parse(row) : null;
  }

  findAll(limit: number, offset: number): Item[] {
    const rows = database
      .prepare(
        "select id, title, user_id from item where deleted_at is null limit ? offset ?",
      )
      .all(limit, offset);

    return rows.map((row) => ItemSchema.parse(row));
  }

  count(): number {
    const row = database
      .prepare("select count(*) as total from item where deleted_at is null")
      .get();

    return Number(row?.total);
  }

  update(item: Item): boolean {
    const result = database
      .prepare(
        "update item set title = ?, user_id = ? where id = ? and deleted_at is null",
      )
      .run(item.title, item.user_id, item.id);

    return result.changes > 0;
  }

  softDelete(id: Item["id"]): boolean {
    const result = database
      .prepare(
        "update item set deleted_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') where id = ?",
      )
      .run(id);

    return result.changes > 0;
  }

  softUndelete(id: Item["id"]): boolean {
    const result = database
      .prepare("update item set deleted_at = null where id = ?")
      .run(id);

    return result.changes > 0;
  }

  hardDelete(id: Item["id"]): boolean {
    const result = database.prepare("delete from item where id = ?").run(id);

    return result.changes > 0;
  }
}

export default new ItemRepository();

3. Param converter and validators

The param converter loads the item named in the URL into req.item, and answers 404 (or 204 on DELETE) if it does not exist:

// src/express/modules/item/itemParamConverter.ts
declare global {
  namespace Express {
    interface Request {
      item: Item;
    }
  }
}

import { createParamConverter } from "../../helpers/paramConverter";
import itemRepository from "./itemRepository";

export default createParamConverter(itemRepository, "item");

Validators check client input, then inject trusted values on the server side:

// src/express/modules/item/itemValidators.ts
import { createValidator } from "../../helpers/validation";
import { ItemDTOSchema } from "./itemSchemas";

const add = createValidator(
  { body: ItemDTOSchema },
  {
    inject: (req) => ({
      user_id: req.me.id, // Trusted from auth middleware
    }),
  },
);

const edit = createValidator(
  { body: ItemDTOSchema },
  {
    inject: (req) => ({
      id: req.item.id, // Trusted from param converter
      user_id: req.me.id, // Trusted from auth middleware
    }),
  },
);

export default {
  add,
  edit,
};

4. Actions

Actions handle HTTP mechanics while delegating database queries to the repository. browse implements HTTP Range semantics (see Pagination for the details):

// src/express/modules/item/itemActions.ts
import type { RequestHandler } from "express";

import itemRepository from "./itemRepository";

const browse: RequestHandler = (req, res) => {
  res.setHeader("Accept-Ranges", "items");

  const match = req.headers.range?.match(/^items=(\d+)-(\d+)$/);

  if (!match) {
    res.sendStatus(400);
    return;
  }

  const [start, end] = [Number(match[1]), Number(match[2])];

  const total = itemRepository.count();

  if (total === 0) {
    res.setHeader("Content-Range", "items */0");
    res.status(200).json([]);

    return;
  }

  if (start < 0 || start > end || start >= total) {
    res.setHeader("Content-Range", `items */${total}`);
    res.sendStatus(416);

    return;
  }

  const limit = end - start + 1;
  const items = itemRepository.findAll(limit, start);

  res.setHeader(
    "Content-Range",
    `items ${start}-${Math.min(end, total - 1)}/${total}`,
  );
  res.status(206).json(items);
};

const read: RequestHandler = (req, res) => {
  res.json(req.item);
};

const edit: RequestHandler = (req, res) => {
  itemRepository.update(req.body);

  res.sendStatus(204);
};

const add: RequestHandler = (req, res) => {
  const insertId = itemRepository.create(req.body);

  res.status(201).json({ insertId });
};

const destroy: RequestHandler = (req, res) => {
  itemRepository.softDelete(req.item.id);

  res.sendStatus(204);
};

export default {
  browse,
  read,
  edit,
  add,
  destroy,
};

5. Route definitions & The Authentication Wall

The module entry point (itemRoutes.ts) creates an isolated router instance. StartER utilizes an Authentication Wall to cleanly separate public endpoints from protected ones:

// src/express/modules/item/itemRoutes.ts
import { type RequestHandler, Router } from "express";
import authActions from "../auth/authActions";
import itemActions from "./itemActions";
import itemParamConverter from "./itemParamConverter";
import itemValidators from "./itemValidators";

const router = Router();
const BASE_PATH = "/api/items";
const ITEM_PATH = "/api/items/:itemId";

// Resolve :itemId into req.item (404 if missing, 204 on DELETE)
router.param("itemId", itemParamConverter.convert);

// Only the owner can change an item
const checkAccess: RequestHandler = (req, res, next) => {
  if (req.item.user_id === req.me.id) {
    next();
  } else {
    res.sendStatus(403);
  }
};

// ── 1. Public routes (no authentication required) ───────────────
router.get(BASE_PATH, itemActions.browse);
router.get(ITEM_PATH, itemActions.read);

// ── 2. Authentication wall ──────────────────────────────────────
router.use(BASE_PATH, authActions.verifyAccessToken);

// ── 3. Authenticated routes (everything below requires login) ───
router.post(BASE_PATH, itemValidators.add, itemActions.add);

router
  .route(ITEM_PATH)
  .all(checkAccess)
  .put(itemValidators.edit, itemActions.edit)
  .delete(itemActions.destroy);

export default router;

6. Registering module routes

Mount your module router in the root src/express/routes.ts:

// src/express/routes.ts
import itemRoutes from "./modules/item/itemRoutes";

router.use(itemRoutes);

Tip

For deep-dives into backend mechanics, see The Repository pattern, Express API and validation, and Pagination.

Step 3: The frontend with React

Frontend components live in src/react/components/<resource>/, providing a full CRUD interface. Here is an example for the item resource:

src/react
├── routes.tsx
└── components
    └── item
        ├── index.tsx           # RouteObject definitions
        ├── ItemForm.tsx        # Shared accessible form with Zod validation
        ├── ItemList.tsx        # Browsing list view (with pagination)
        ├── ItemShow.tsx        # Single entity detail view
        ├── ItemCreate.tsx      # Creation view wrapping ItemForm
        ├── ItemEdit.tsx        # Edit view wrapping ItemForm
        └── ItemDeleteForm.tsx  # Deletion action button

1. The shared, accessible ItemForm

A single ItemForm component handles both creation and editing, complete with client-side Zod validation and full accessibility attributes:

// src/react/components/item/ItemForm.tsx
import { type PropsWithChildren, useId, useState } from "react";
import { z } from "zod";
import type { $ZodIssue as ZodIssue } from "zod/v4/core";
import { FormError, hasError } from "../FormError";

type ItemFormValues = Pick<Item, "title">;

const ItemFormSchema: z.ZodType<ItemFormValues> = z.object({
  title: z.string().min(1, "Title is required"),
});

interface ItemFormProps extends PropsWithChildren {
  defaultValue: Omit<Item, "id" | "user_id">;
  action: (partialItem: Omit<Item, "id" | "user_id">) => void;
}

function ItemForm({ children, defaultValue, action }: ItemFormProps) {
  const titleId = useId();
  const [errors, setErrors] = useState<ZodIssue[]>([]);

  return (
    <form
      aria-label="item form"
      action={(formData) => {
        const parsed = ItemFormSchema.safeParse(Object.fromEntries(formData));

        if (!parsed.success) {
          setErrors(parsed.error.issues);
          return;
        }

        setErrors([]);
        action(parsed.data);
      }}
    >
      <p>
        <label htmlFor={titleId}>title</label>
        <input
          id={titleId}
          type="text"
          name="title"
          defaultValue={defaultValue.title}
          aria-invalid={hasError(errors, "title") || undefined}
          aria-describedby={`${titleId}-error`}
        />
        <FormError issues={errors} name="title" id={`${titleId}-error`} />
      </p>
      {children}
    </form>
  );
}

export default ItemForm;

2. Creating and Editing with mutate()

ItemCreate and ItemEdit supply initial data and submission handlers to ItemForm:

// src/react/components/item/ItemCreate.tsx
import { useCallback } from "react";
import { useNavigate } from "react-router";

import { mutate } from "../../helpers/mutate";
import ItemForm from "./ItemForm";

function ItemCreate() {
  const navigate = useNavigate();

  const addItem = useCallback(
    async (partialItem: Omit<Item, "id" | "user_id">) => {
      const response = await mutate("/api/items", "post", partialItem, [
        "/api/items",
      ]);

      const { insertId } = await response.json();

      navigate(`/items/${insertId}`);
    },
    [navigate],
  );

  const newItem = {
    title: "",
  };

  return (
    <ItemForm defaultValue={newItem} action={addItem}>
      <button type="submit">Add</button>
    </ItemForm>
  );
}

export default ItemCreate;
// src/react/components/item/ItemEdit.tsx
import { use, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import { getOrFetch, useRefresh } from "../../helpers/cache";
import { mutate } from "../../helpers/mutate";
import ItemForm from "./ItemForm";

function ItemEdit() {
  const navigate = useNavigate();
  const { id } = useParams();

  useRefresh(`/api/items/${id}`);

  const editItem = useCallback(
    async (partialItem: Omit<Item, "id" | "user_id">) => {
      await mutate(`/api/items/${id}`, "put", partialItem, [
        "/api/items",
        `/api/items/${id}`,
      ]);

      navigate(`/items/${id}`);
    },
    [id, navigate],
  );

  const item = use(getOrFetch<Item>(`/api/items/${id}`));

  return (
    <ItemForm defaultValue={item} action={editItem}>
      <button type="submit">Edit</button>
    </ItemForm>
  );
}

export default ItemEdit;

3. Browsing items (ItemList.tsx)

The ItemList component retrieves and displays items with pagination using use(getOrFetch(...)). The link to create an item is only shown to authenticated users:

// src/react/components/item/ItemList.tsx
import { use } from "react";
import { Link, useSearchParams } from "react-router";
import { getOrFetch, useRefresh } from "../../helpers/cache";
import { parseContentRangeTotal } from "../../helpers/pagination";
import { useMe } from "../auth/MeContext";
import Pagination from "../Pagination";

const PAGE_SIZE = 10;

function ItemList() {
  useRefresh("/api/items");

  const { isAuthenticated } = useMe();

  const [searchParams] = useSearchParams();
  const page = Number(searchParams.get("page")) || 1;
  const start = (page - 1) * PAGE_SIZE;
  const end = start + PAGE_SIZE - 1;

  const { items, total } = use(
    getOrFetch<{ items: Item[]; total: number }>("/api/items", {
      headers: { Range: `items=${start}-${end}` },
      parse: async (res) => ({
        items: await res.json(),
        total: parseContentRangeTotal(res.headers.get("Content-Range")),
      }),
    }),
  );

  return (
    <>
      <h1>Items</h1>
      {isAuthenticated && (
        <Link to="/items/new" data-testid="items-new">
          Add
        </Link>
      )}

      <ul>
        {items.map((item) => (
          <li key={item.id}>
            <Link to={`/items/${item.id}`}>{item.title}</Link>
          </li>
        ))}
      </ul>
      <Pagination total={total} pageSize={PAGE_SIZE} currentPage={page} />
    </>
  );
}

export default ItemList;

4. Details and Deletion (ItemShow.tsx & ItemDeleteForm.tsx)

ItemShow displays a single item and, for its owner only, the edit link and ItemDeleteForm:

// src/react/components/item/ItemShow.tsx
import { use } from "react";
import { Link, useParams } from "react-router";
import { getOrFetch, useRefresh } from "../../helpers/cache";
import { useMe } from "../auth/MeContext";
import ItemDeleteForm from "./ItemDeleteForm";

function ItemShow() {
  const { user } = useMe();
  const { id } = useParams();

  useRefresh(`/api/items/${id}`);

  const item = use(getOrFetch<Item>(`/api/items/${id}`));

  return (
    <>
      <h1>{item.title}</h1>
      {user?.id === item.user_id && (
        <>
          <Link
            to={`/items/${item.id}/edit`}
            data-testid={`items-edit-${item.id}`}
          >
            Edit
          </Link>
          <ItemDeleteForm />
        </>
      )}
    </>
  );
}

export default ItemShow;
// src/react/components/item/ItemDeleteForm.tsx
import { useCallback } from "react";
import { useNavigate, useParams } from "react-router";

import { mutate } from "../../helpers/mutate";

function ItemDeleteForm() {
  const navigate = useNavigate();
  const { id } = useParams();

  const deleteItem = useCallback(async () => {
    await mutate(`/api/items/${id}`, "delete", null, [
      "/api/items",
      `/api/items/${id}`,
    ]);

    navigate("/items");
  }, [id, navigate]);

  return (
    <form action={deleteItem}>
      <button type="submit">Delete</button>
    </form>
  );
}

export default ItemDeleteForm;

5. Registering React routes

Export route definitions from src/react/components/item/index.tsx and register them in src/react/routes.tsx:

// src/react/components/item/index.tsx
import type { RouteObject } from "react-router";

import ItemCreate from "./ItemCreate";
import ItemEdit from "./ItemEdit";
import ItemList from "./ItemList";
import ItemShow from "./ItemShow";

export const itemRoutes: RouteObject[] = [
  {
    path: "/items/new",
    element: <ItemCreate />,
  },
  {
    path: "/items/:id/edit",
    element: <ItemEdit />,
  },
  {
    path: "/items",
    element: <ItemList />,
  },
  {
    path: "/items/:id",
    element: <ItemShow />,
  },
];
// src/react/routes.tsx
import { itemRoutes } from "./components/item/index";

// ...

children: [
  {
    errorElement: <ErrorPage />,
    children: [
      // ...
      ...itemRoutes,
    ],
  },
],

Step 4: Verification

Once your database table, backend module, and React components are in place, run the verification suite:

# Type check TypeScript files
npm run types:check

# Verify code formatting and linting
npm run biome:check

# Run test suite & API contracts
npm run test

Tip

To test your new resource with StartER's contract system, define mock data and a seeder in tests/fixtures/<resource>.ts, register it in tests/fixtures/index.ts, and create the declarative contract in tests/contracts/<resource>.ts. See Contracts and verification for details.

Best practices and use cases

  • One file = one responsibility: Separate route definitions from request handlers and database operations.
  • Modular architecture: Group all files belonging to the same resource in a dedicated directory rather than scattering them across global folders.
  • Reusable forms: Centralize form fields and client-side validation in a single <ResourceForm> shared by creation and edit views.
  • Accessibility from day one: Always pair inputs with <label htmlFor> and add aria-invalid and aria-describedby attributes for error states.

See also

Clone this wiki locally