Repository navigation
Recipes
Summary: Short answers to the questions that come up first when you build an application with StartER. Each recipe shows the code to change and links to the page that explains the mechanism.
What you'll learn:
- Show pages to visitors who aren't logged in
- Show API errors in a form
- Handle number, checkbox and date fields
- Keep non-owners off a page
- Test your app from a phone or another computer
- Give some users an admin role
- Filter a list with a search field
- Add an environment variable used in the browser
- Send your own emails
- Get framework fixes into your project
Important
make:purge removes the example modules by matching the original code of files such as Layout.tsx and NavBar.tsx. If you plan to run it, do it before applying these recipes.
By default, Layout.tsx shows the login form, instead of the page, to visitors who aren't logged in. Only /verify escapes this rule. The API is not involved: GET /api/items is public, while the /items page is not. List the pages that should be public:
// src/react/components/Layout.tsx
import { matchPath, Outlet, useLocation } from "react-router";
// ...
// Pages that visitors who aren't logged in can see
const publicPaths = ["/verify", "/items", "/items/:id"];
function Layout() {
const { isAuthenticated } = useMe();
const location = useLocation();
const isPublic = publicPaths.some((path) =>
matchPath(path, location.pathname),
);
// ...
{isAuthenticated || isPublic ? (To show their link in the navigation bar, move it out of the isAuthenticated block in NavBar.tsx:
// src/react/components/NavBar.tsx
{link("/", "Home")}
{link("/items", "Items")}
{isAuthenticated && (A public page can still show some actions to logged-in users only: ItemList hides its Add link from visitors, and ItemShow shows its Edit and Delete buttons to the owner only. Cover the new rule in tests/react/components/auth/Layout.test.tsx:
// tests/react/components/auth/Layout.test.tsx
it("should render public pages when not authenticated", async () => {
await renderWithStub({
path: "/items",
Component: Layout,
initialEntries: ["/items"],
me: null,
});
await screen.findByRole("navigation");
expect(screen.queryByLabelText(/email/i)).toBeNull();
});See Authentication and Authorization.
mutate() throws when the API answers with an error status. If your code doesn't catch it, the user gets no useful feedback: in ItemCreate and ItemEdit, the form stays as it is and the error only appears in the browser console, because ItemForm doesn't wait for your action. In ItemDeleteForm, the error page replaces the whole page. Catch the error in the action and show it:
// src/react/components/item/ItemCreate.tsx
import { useCallback, useState } from "react";
// ...
const [error, setError] = useState<string | null>(null);
const addItem = useCallback(
async (partialItem: Omit<Item, "id" | "user_id">) => {
try {
const response = await mutate("/api/items", "post", partialItem, [
"/api/items",
]);
const { insertId } = await response.json();
navigate(`/items/${insertId}`);
} catch (err) {
// mutate() throws "<status>: <status text>", e.g. "409: Conflict"
setError(err instanceof Error ? err.message : String(err));
}
},
[navigate],
);
// ...
<ItemForm defaultValue={newItem} action={addItem}>
{error && <p role="alert">{error}</p>}
<button type="submit">Add</button>
</ItemForm>Test it by making fetch answer with an error:
// tests/react/components/item/ItemCreate.test.tsx
it("should show the error when the API refuses the item", async () => {
const { user } = await renderWithStub({
path: "/items/new",
Component: ItemCreate,
initialEntries: ["/items/new"],
me: standardUser,
});
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(null, { status: 409, statusText: "Conflict" }),
);
await user.type(screen.getByLabelText(/title/i), "new title");
await user.click(screen.getByRole("button"));
expect((await screen.findByRole("alert")).textContent).toBe(
"409: Conflict",
);
});To handle one status differently, test the message, for example err.message.startsWith("409"). See Error handling.
Form values are strings, and an unchecked checkbox isn't sent at all. Convert them in the Zod schema of the form, in ItemForm.tsx, so that the action receives the right types:
const ItemFormSchema = z.object({
title: z.string().min(1, "Title is required"),
// <input type="number" name="quantity" />: "3" becomes 3
quantity: z.coerce.number().int().min(0),
// <input type="checkbox" name="done" />: "on" when checked, absent when not
done: z.coerce.boolean().default(false),
});- An empty number field becomes
0: use.min(1)if the field is required. - The server schema stays
z.number():mutate()sends JSON numbers. - SQLite has no boolean type, and
node:sqliterefuses JavaScript booleans: storeNumber(item.done)in the repository, and read the column withz.coerce.boolean()in the entity schema. - For dates and times, use the helpers of Date management.
First exercises (Exercise 4) adds a field across the whole stack. See also Using Zod.
The API refuses changes from anyone but the owner, with 403. Yet a page such as /items/1/edit still opens for anyone, and the failure only shows when the form is submitted. Check ownership in the page, as ItemShow does for its buttons:
// src/react/components/item/ItemEdit.tsx
import { useMe } from "../auth/MeContext";
// ...
const { user } = useMe();
// ...
const item = use(getOrFetch<Item>(`/api/items/${id}`));
if (user?.id !== item.user_id) {
return <p>Only the owner of this item can edit it.</p>;
}Test it with another user:
// tests/react/components/item/ItemEdit.test.tsx
it("should not show the form to other users", async () => {
await renderWithStub({
path: "/items/:id/edit",
Component: ItemEdit,
initialEntries: [`/items/${allItems[0].id}/edit`],
me: userWithAvatar,
});
await screen.findByText(/only the owner/i);
expect(screen.queryByRole("button")).toBeNull();
});See Authorization.
Opened through your machine's network address, such as http://192.168.1.45:5173, the app shows its pages, but logging in and every change fail, and the browser console shows cookieStore is not defined. Browsers only provide cookieStore, which mutate() uses for the CSRF token, on HTTPS or on localhost, and the __Host- cookies require the same.
Make the other device reach the app through its own localhost:
# Android phone connected by USB, with USB debugging enabled
adb reverse tcp:5173 tcp:5173
# Another computer
ssh -L 5173:localhost:5173 you@your-dev-machineThen open http://localhost:5173 on that device. Otherwise, put the app behind HTTPS, as in production (see Deployment).
Note
Chrome's setting that treats an insecure origin as secure is not enough: the __Host- cookies are still rejected over HTTP.
- Add a
rolecolumn to theusertable inschema.sql, then runnpm run database:reset:
-- src/database/schema.sql
create table user (
-- ...
avatar_url text default null,
role varchar(20) not null default 'user',- Add it to
UserSchema, and keep it out of the DTO: otherwise any user could sendrole: "admin"when editing their account.
// src/express/modules/user/userSchemas.ts
export const UserSchema = z.object({
// ...
role: z.enum(["user", "admin"]),
});
// ...
export const UserDTOSchema = UserSchema.omit({
id: true,
avatar_url: true,
role: true, // Never let users choose their own role
});- Select it in the two queries of
userRepository.tsthat read a user,findandfindByEmail:
// src/express/modules/user/userRepository.ts
"select id, email, name, avatar_url, role from user where id = ? and deleted_at is null",-
Add
"role"to the twoOmit<User, ...>types ofMeContext.tsx. -
Use it. For example, let admins edit any item:
// src/express/modules/item/itemRoutes.ts
const checkAccess: RequestHandler = (req, res, next) => {
if (req.item.user_id === req.me.id || req.me.role === "admin") {Or protect a whole section with a requireRole middleware, next to verifyAccessToken:
// src/express/modules/auth/authActions.ts
/*
Allow only users with the given role. Runs after verifyAccessToken.
*/
const requireRole =
(role: User["role"]): RequestHandler =>
(req, res, next) => {
if (req.me.role === role) {
next();
} else {
res.sendStatus(403);
}
};
// ...
export default {
// ...
verifyAccessToken,
requireRole,
};router.use(
"/api/admin",
authActions.verifyAccessToken,
authActions.requireRole("admin"),
);To make someone an admin, run npm run database:repl, then:
update user set role = 'admin' where email = 'you@mail.com'In the tests, add role: "user" to the user fixtures, add an admin to allUsers, insert the role in seedUsers, and cover the new rule with a contract case:
// tests/fixtures/users.ts
export const adminUser: User = Object.freeze({
id: 6,
email: "admin@mail.com",
name: "admin",
avatar_url: null,
role: "admin",
});
// ...
const insertUser = db.prepare(
"insert into user(id, email, name, avatar_url, role) values(?, ?, ?, ?, ?)",
);// tests/contracts/items.ts
as_admin: {
request: {
body: { title: "updated title" },
jwtPayload: { sub: adminUser.id },
},
response: { status: 204, body: {} },
},See Authorization and Contracts and verification.
Send the search to the API as a query parameter. In the browser, keep it in the page URL, as the page number is for pagination.
- Validate the parameter, and add the validator to the route:
// src/express/modules/item/itemValidators.ts
import { z } from "zod";
// ...
const browse = createValidator({
query: z.object({ q: z.string().trim().max(100).optional() }),
});
// ...
export default {
browse,
add,
edit,
};// src/express/modules/item/itemRoutes.ts
router.get(BASE_PATH, itemValidators.browse, itemActions.browse);- Filter in the repository, in both
findAllandcount, so that the total matches the results:
// src/express/modules/item/itemRepository.ts
findAll(limit: number, offset: number, q?: string): Item[] {
const rows = database
.prepare(
"select id, title, user_id from item where deleted_at is null and ($q is null or instr(lower(title), lower($q)) > 0) limit $limit offset $offset",
)
.all({ q: q ?? null, limit, offset });
return rows.map((row) => ItemSchema.parse(row));
}
count(q?: string): number {
const row = database
.prepare(
"select count(*) as total from item where deleted_at is null and ($q is null or instr(lower(title), lower($q)) > 0)",
)
.get({ q: q ?? null });
return Number(row?.total);
}- Pass the parameter from the action:
// src/express/modules/item/itemActions.ts
const { q } = req.query as { q?: string };
const total = itemRepository.count(q);
// ...
const items = itemRepository.findAll(limit, start, q);- Send it from the page, with a search form:
// src/react/components/item/ItemList.tsx
import { Form, Link, useSearchParams } from "react-router";
// ...
const q = searchParams.get("q") ?? "";
const url = q ? `/api/items?${new URLSearchParams({ q })}` : "/api/items";
// ...
getOrFetch<{ items: Item[]; total: number }>(url, {
// ...
<Form role="search">
<input type="search" name="q" defaultValue={q} aria-label="Search" />
<button type="submit">Search</button>
</Form>instr(lower(title), lower($q)) finds the text anywhere in the title, without the escaping that like needs for % and _. Pagination keeps q when changing page.
Test it with a contract case, then from the page:
// tests/contracts/items.ts
search: {
specialPath: "/api/items?q=stuff",
request: { headers: { Range: "items=0-9" } },
response: {
status: 206,
body: [firstItem],
headers: { "content-range": "items 0-0/1" },
},
},// tests/react/components/item/ItemList.test.tsx
it("should search items", async () => {
await renderWithStub({
path: "/items",
Component: ItemList,
initialEntries: ["/items?q=stuff"],
me: standardUser,
});
await screen.findByRole("heading", { level: 1, name: /items/i });
expectContractCall("items", "browse", "search");
});See Pagination and Express API and validation.
Only variables whose name starts with VITE_ reach the browser. Declare them in the client schema, with a default:
// src/env/client.ts
export const clientEnvSchema = z.object({
VITE_APP_NAME: z.string().default("StartER"),Then use them anywhere through clientEnv:
// src/react/components/Home.tsx
import { clientEnv } from "../../env/client";
// ...
<h1>{clientEnv.VITE_APP_NAME}</h1>List them in .env.sample. Their values are written into the built files: after changing one, run npm run build again. Never put a secret in a VITE_ variable, because anyone can read it in the browser. For server variables, see the environment section of Directory structure.
The SMTP connection lives in authActions.ts, for magic links. Move it to a helper, so that any module can send emails:
// src/express/helpers/mail.ts
import nodemailer from "nodemailer";
import { serverEnv } from "../../env/server";
const transporter = serverEnv.SMTP_URL
? nodemailer.createTransport({
url: serverEnv.SMTP_URL,
...(serverEnv.DKIM_PRIVATE_KEY &&
serverEnv.DKIM_DOMAIN && {
dkim: {
domainName: serverEnv.DKIM_DOMAIN,
keySelector: serverEnv.DKIM_SELECTOR,
privateKey: serverEnv.DKIM_PRIVATE_KEY,
},
}),
})
: null;
/*
Sends an email, or returns false when no SMTP server is configured:
in development, the caller can then print what it would have sent.
*/
export const sendMail = async (message: {
to: string;
subject: string;
html: string;
}): Promise<boolean> => {
if (transporter == null) {
return false;
}
await transporter.sendMail({ from: "starter@mail.com", ...message });
return true;
};In authActions.ts, remove transporter and the nodemailer import, then send the magic link with the helper. The development fallback, which prints the link in the terminal, doesn't change:
// src/express/modules/auth/authActions.ts
import { sendMail } from "../../helpers/mail";
// ...
const sent = await sendMail({
to: email,
subject: "Login link",
html: `<a href="${magicLink}">Click here to login</a>`,
});
if (!sent) {Then, in any action:
await sendMail({
to: user.email,
subject: "Welcome!",
html: "<p>Welcome aboard.</p>",
});Without SMTP_URL, sendMail sends nothing and returns false. See Authentication for the SMTP and DKIM settings.
A project created from the template has its own history, with no link to StartER. To pick up a fix later, add StartER as a second remote, then cherry-pick the commits you want:
git remote add starter https://github.com/rocambille/start-express-react.git
git fetch starter --tags
# What changed between two releases
git log --oneline --no-merges v2026.11.01..v2026.11.04
# Apply one commit: here, the session lifetime fix of v2026.11.04
git cherry-pick 8613548Releases are tagged with their date. A cherry-pick applies the changes of one commit to your files: if you changed the same lines, Git stops on a conflict for you to resolve.
AI co-creation
Getting started
Explanations
How-To Guides
Reference
Digging deeper