Ch 5 · Your Own API · Next.js

Topic 5 of 7 in Next.js — Build the App You Deploy — 4 lessons.

Route Handlers

A file named route.js gives you an HTTP endpoint instead of a page.

Reading a Request Body

Read that validation carefully. Everything arriving in a request is hostile until checked — not because your client is malicious, but because browsers, mobile apps and typos all send things you did not plan for. The type check, the trim, the Number.isNaN, the range check: four lines that prevent a bad row reaching the database.

Status Codes That Mean Something

Returning 200 with { "error": "..." } inside it is a habit worth avoiding. Every tool that consumes your API — including your own front end, and the res.ok check from Card 4.1 — decides success by the status code first.

Do You Even Need One?

If a server component can read the database directly, why write an API at all?

All topics in Next.js Beginner

  1. What Next.js Adds
  2. Routes Are Folders
  3. Server and Client
  4. Getting Data Onto the Page
  5. Your Own API
  6. Talking to Postgres
  7. The Project