Route Handlers
Part of the Next.js Essentials section of Coddy's React journey — lesson 37 of 47.
Server components cover most data needs, because they run on the server already. But sometimes the browser has to ask for data later, after a click, after a search box settles, and for that you need an endpoint to call.
A folder with a route.js in it becomes exactly that. Same routing rule as pages, different special file:
app/
api/
dishes/
route.js -> /api/dishesInside, you export a function named after the HTTP method:
import { dishes } from '../../../lib/dishes.js';
export async function GET() {
return Response.json(dishes);
}Response.json(...) is the whole reply: it serialises the value and sets the JSON content type. You can export POST, PUT, DELETE from the same file too.
Then the client half is ordinary browser code:
const res = await fetch('/api/dishes');
const data = await res.json();Two things to keep straight. A folder can hold a page.jsx or a route.js, never both: they'd both claim the same URL. And route.js is not a component: it returns a Response, not JSX.
Reach for a route handler when the browser needs data on demand, or when something outside your app needs to call in. If a server component can just read the data while rendering, let it.
Challenge
MediumBuild a tiny API and call it from the browser.
- In
app/api/dishes/route.js, export anasync function GETthat returnsdishesas JSON. - In
components/DishLoader.jsx, finishloadDishes: fetch/api/dishes, read the JSON body, and store the dish names withsetNames.
Clicking #load-btn must fill #dish-list with all four names.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
4Server & Client
Two Kinds of ComponentReading the ErrorThe 'use client' LineKeep Client Parts SmallServer Inside ClientRecap: Server & Client7Client Navigation
The Active LinkProgrammatic RoutingFiltering with the URLRoute HandlersRecap: Navigation