Source: https://github.com/7flash/TradJS · bun add tradjs
Files are routes#
| File | Answers |
|---|---|
app/page.tsx |
GET / |
app/notes/page.tsx |
GET /notes |
app/notes/[id]/page.tsx |
GET /notes/42 with params.id = "42" |
app/api/notes/route.ts |
GET/POST /api/notes (export functions named after methods) |
app/layout.tsx |
wraps every page below it |
app/middleware.ts |
runs before pages and routes below it |
app/not-found.tsx, app/error.tsx |
custom 404 and 500 pages |
public/robots.txt |
served as a file |
Middleware hands typed values to pages#
// app/middleware.ts
export default function middleware(req: Request, ctx: RouteContext<AppLocals>) {
ctx.locals.user = readSession(req);
if (new URL(req.url).pathname === "/notes" && !ctx.locals.user) return redirect("/login", 302);
}
// app/notes/page.tsx
export default function Notes({ locals }: PageProps<AppLocals>) {
return <ul>{notesFor(locals.user!.id).map((n) => <li key={n.id}>{n.text}</li>)}</ul>;
}
Browser scripts mount where needed#
// app/notes/page.client.tsx
export default function mount() {
const timer = setInterval(refresh, 1000);
return () => clearInterval(timer); // stopped when the page is hidden, restarted on return
}
Security that is on by default#
- Cross-site writes are refused. A
POST/PUT/PATCH/DELETEcarrying cookies from another origin gets403. - Unsafe content never reaches the page.
javascript:/vbscript:/data:links,srcdocand unsafe style URLs are dropped, on the server and in the browser, on first render and on updates. - Production errors reveal no details; development errors show them.
- The public folder is locked down: no dotfiles and no path traversal in any encoding.
Static pages#
export const ssg = true prerenders a page at startup, and ssgParams() lists the parameter values. A static page behind middleware still runs the middleware on each request, and is rendered with empty locals, so one visitor's data can never appear in the shared page.
Next: chapter 4, the data layer.