Skip to content

Route Handlers

The Course
•
20 min study

Pages for people, APIs for programs

Pages answer with HTML for people to read. Sometimes a program needs your data instead: a phone app, another website, or a script. It wants plain data, usually JSON. A route handler answers a request with whatever you return, without a page around it.

An API endpoint Next.js · 6 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Hub</header> {children} </body> </html> ); } import TopicLoader from "./TopicLoader.jsx"; export default function HomePage() { return ( <main> <h1>Topics from the API</h1> <TopicLoader /> </main> ); } "use client"; import { useState } from "react"; export default function TopicLoader() { const [topics, setTopics] = useState(null); async function load() { const response = await fetch("/api/topics"); setTopics(await response.json()); } return ( <> <button onClick={load}>Load topics</button> {topics && ( <ul> {topics.map((topic) => <li key={topic.slug}>{topic.title}</li>)} </ul> )} </> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } import { getTopics } from "@/lib/topics.js"; // GET /api/topics answers with JSON, not a page. Any program can call it: // this site's own components, a phone app, or another server. export async function GET() { console.log("GET /api/topics"); return Response.json(getTopics()); } // A pretend database of topics, in the server's memory. const topics = [ { slug: "routing", title: "Routing", day: 1 }, { slug: "server-components", title: "Server components", day: 2 }, { slug: "dynamic-routes", title: "Dynamic routes", day: 3 }, ]; export function getTopics() { return topics; } export function getTopic(slug) { return topics.find((topic) => topic.slug === slug) ?? null; } export function addTopic(topic) { topics.push(topic); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

Press Load topics.

route.js

JavaScript
export async function GET() {
  return Response.json(getTopics());
}

A file named route.js makes an endpoint at its folder's address, here /api/topics. Each exported function handles one kind of request, named after the HTTP method: GET to read, POST to create, and so on. It returns a Response; Response.json(data) turns data into JSON.

Putting APIs under app/api/ is a convention, not a rule, and it keeps them apart from pages. A folder can't have both a page.jsx and a route.js.

Calling it

JavaScript
const response = await fetch("/api/topics");
setTopics(await response.json());

TopicLoader is a client component, so it fetches in the browser, in a click handler. Server components don't need an API to reach their own data: they call getTopics() directly, as on Day 4. Route handlers are for code outside your server components: client components, other apps, other people.

Predict

Type /api/topics into the preview's address bar.

Check your prediction

The JSON itself, with 200 · application/json above it: the status code and the kind of answer. A browser can show any answer, not only pages. On your own computer, http://localhost:3000/api/topics shows the same JSON.

Exercise

Filter by day

Let callers ask for one day's topics with /api/topics?day=2, and make the button load only Day 2's.

Your working space Next.js · 6 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Hub</header> {children} </body> </html> ); } import TopicLoader from "./TopicLoader.jsx"; export default function HomePage() { return ( <main> <h1>Topics from the API</h1> <TopicLoader /> </main> ); } "use client"; import { useState } from "react"; export default function TopicLoader() { const [topics, setTopics] = useState(null); async function load() { const response = await fetch("/api/topics"); setTopics(await response.json()); } return ( <> <button onClick={load}>Load topics</button> {topics && ( <ul> {topics.map((topic) => <li key={topic.slug}>{topic.title}</li>)} </ul> )} </> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } import { getTopics } from "@/lib/topics.js"; // GET /api/topics answers with JSON, not a page. Any program can call it: // this site's own components, a phone app, or another server. export async function GET() { console.log("GET /api/topics"); return Response.json(getTopics()); } // A pretend database of topics, in the server's memory. const topics = [ { slug: "routing", title: "Routing", day: 1 }, { slug: "server-components", title: "Server components", day: 2 }, { slug: "dynamic-routes", title: "Dynamic routes", day: 3 }, ]; export function getTopics() { return topics; } export function getTopic(slug) { return topics.find((topic) => topic.slug === slug) ?? null; } export function addTopic(topic) { topics.push(topic); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

A route handler reads the query string from the request it's given, much as a page reads searchParams. Filtering belongs on the server, so the browser only downloads the topics it shows.

Hint 2: a first step

Give GET a request parameter. new URL(request.url).searchParams.get("day") is "2" for /api/topics?day=2, or null with no day. Log it, then visit /api/topics?day=2 in the preview's address bar before you filter.

Show one solution
JavaScript
export async function GET(request) {
  const day = new URL(request.url).searchParams.get("day");
  const topics = getTopics();
  return Response.json(day ? topics.filter((topic) => topic.day === Number(day)) : topics);
}
JavaScript
const response = await fetch("/api/topics?day=2");

get returns a string or null, so Number(day) is needed to compare with topic.day, and null means every topic, so /api/topics still works for other callers. The button only changes the address it asks for; the server decides what to send.

Was this article helpful?

Your response is saved on this device.