Menu
Coddy logo textTech

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/dishes

Inside, 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 icon

Challenge

Medium

Build a tiny API and call it from the browser.

  1. In app/api/dishes/route.js, export an async function GET that returns dishes as JSON.
  2. In components/DishLoader.jsx, finish loadDishes: fetch /api/dishes, read the JSON body, and store the dish names with setNames.

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>
    );
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Next.js Essentials