You've built the whole To-Do API: sign-up, login, five task endpoints on PostgreSQL, and 22 tests that check it all. This lesson collects the best practices we used along the way (and a few more) into one checklist you can use on every API you build.
What we built
tasks-api/ βββ prisma/ schema.prisma, migrations/ βββ src/ β βββ server.ts Β· app.ts β βββ config/env.ts β βββ lib/prisma.ts β βββ middlewares/ auth.ts Β· validate.ts Β· error-handler.ts β βββ utils/http-error.ts β βββ modules/ β βββ auth/ routes Β· controller Β· service Β· schema β βββ tasks/ routes Β· controller Β· service Β· schema βββ tests/ helpers Β· *.test.ts (22 tests) Β· .env.test βββ .env (secret) Β· .env.example (committed) βββ package.json Β· tsconfig.json
The 12 best practices
Input and output
- Never trust input. Validate every body with Zod on the server. Anyone can call your API with curl, skipping your frontend completely.
- Return the right status code. 201 for created, 204 for deleted, 400 for bad input, 401/403 for auth, 404 for missing. Apps rely on these.
- Use one response shape. Success returns the data; every error returns
{ "error": "message" }. The app then handles all errors the same way. - Never send secrets back. No passwords, hashes or internal ids the user shouldn't see. Use
selectin Prisma.
Errors
- Handle errors in one place. Services
throw new HttpError(404, "β¦"); the error handler sends the response. No copy-pasted try/catch. - Never leak internals. Log the full error for yourself, but show users only βSomething went wrongβ with a 500.
Security
- Secrets live in .env. Check them at startup (
config/env.ts), commit only.env.example. - Hash passwords with bcrypt. Never store or log a real password.
- Always filter by the logged-in user.
where: { id, userId }in every query on user data. - Add safety middleware:
helmet()for safe headers,cors()to choose which websites can call you, and a rate limiter on login.
Rate limiting is one package and two lines. Install it with bun add express-rate-limit:
import rateLimit from "express-rate-limit";
// At most 20 login/register attempts per 15 minutes from one IP address
app.use("/api/auth", rateLimit({ windowMs: 15 * 60 * 1000, limit: 20 }));
app.use("/api/auth", authRouter);We tested it: the first 20 wrong logins got 401, and from the 21st on the API answered:
Too many requests, please try again later.Code and database
- Keep the structure. One folder per feature; routes β controller β service. Services never see req/res; controllers never touch the database.
- Change the database only through migrations.
migrate devon your laptop,migrate deployon the server, migrations committed to Git.
Before you call an API βdoneβ
| Check | Ask yourself |
|---|---|
| Validation | What happens if a field is missing, empty, too long, or the wrong type? |
| Auth | What happens with no token, a fake token, or someone else's id? |
| Not found | What happens with an id that doesn't exist, or isn't a number? |
| Status codes | Does each success and each error return the right code? |
| Secrets | Does any response include a password, hash or internal detail? |
| Limits | Can someone ask for a million rows or try a million passwords? |
The cheat sheet
Commands
$bun init -y # new project$bun add express zod # add packages$bun add -d @types/express # add dev-only packages$bun run dev # start with auto-restart$bun check # find type errors$bun run db:migrate --name what_changed # schema change β new migration$bun run db:generate # update the Prisma client$bun run db:studio # look at your data
Status codes
| Code | Use it when |
|---|---|
| 200 | OK: here's the data (GET, PATCH) |
| 201 | Created something (POST) |
| 204 | Done, nothing to return (DELETE) |
| 400 | Bad input or broken JSON |
| 401 | Not logged in or token invalid |
| 403 | Logged in but not allowed |
| 404 | Doesn't exist (or isn't yours) |
| 409 | Conflict, e.g. email already used |
| 429 | Too many requests |
| 500 | Our bug. Log it, show a safe message |
Express in 6 lines
app.use(express.json()); // read JSON bodies
app.get("/path/:id", handler); // route with a URL parameter
req.params.id Β· req.query.page Β· req.body // the three kinds of input
res.status(201).json(data); // send a response
(req, res, next) => { ...; next(); } // middleware
app.use(errorHandler); // error handler, always lastWhere to go next
- Practice: add the due-date field from the database lesson to the API, with a filter
?due=today. - Build your own: a notes app, an expense tracker or a blog API, using exactly this structure.
- Learn next: deployment, file uploads and Docker. These are coming to this course.
- Interviews: once you can build APIs, learn how big systems are designed in our System Design course, starting with Design a URL Shortener.
Key takeaways
- βYou built a complete To-Do API: auth, CRUD, validation, errors and a real database.
- βBest practices boil down to: validate input, fail clearly, protect secrets, be predictable, keep structure.
- βRate limiting, helmet and CORS are a few lines each and block common attacks.
- βUse the checklist before calling any endpoint done.
- βKeep the cheat sheet: commands, status codes and the six Express basics.
Frequently asked questions
What are the most important Express best practices?
Validate every input, handle all errors in one place, never leak internal errors to users, keep secrets in .env, use a clear folder structure, return correct status codes, and protect login routes with rate limiting.
Should I use Express or a newer framework?
Express is still the most used Node.js framework and the best first one to learn, because nearly every tutorial, job and library knows it. Newer options like Fastify, Hono or NestJS are easy to pick up once you understand Express.
How do I deploy my Express API?
Push the code to GitHub and use a host that runs Node.js or Bun apps (Railway, Render, Fly.io, or a VPS). Set your .env values in the host's settings, run `prisma migrate deploy` and `prisma generate` during deploy, then start with `bun src/server.ts`.
Do I need to write tests?
Yes. The previous lesson, Testing Your Express API, adds 22 tests with bun test and Supertest: unit tests for the schemas and API tests for every endpoint, on a separate test database, running on every push with GitHub Actions.
What should I learn after this course?
Deploying your API, file uploads, Docker, and refresh tokens for better login. Then build your own project with the same structure: a notes app, a blog API or an expense tracker.
π§ Quick check: best practices
1. A database query fails with a long technical error. What should the user see?
2. Where should input validation happen?
3. Someone tries 1,000 passwords on /api/auth/login. What stops them?
4. Which file should never be committed to Git?
Checking your accessβ¦