1. Route Handlers
Next.js App Router lets you create backend API endpoints right inside your project β no Express, no separate server. You place a special file called route.ts inside the app/api/ directory and export named functions for each HTTP method.
This is called a Route Handler. When a request arrives at that URL, Next.js calls the matching exported function β GET, POST, PUT, or DELETE.
UrbanCart's product catalogue lives in a database. The React frontend needs to fetch product data and let admins create new listings. Instead of spinning up a separate Express server, we place app/api/products/route.ts inside the Next.js project and export GET and POST functions. The frontend calls /api/products β Next.js handles the routing automatically.
folder = URL prefix
subfolder = path segment
export GET, POSTβ¦
route.ts (or route.js). Any other name won't be recognized as a Route Handler. Also, a folder can have either a page.tsx (UI) or a route.ts (API), but not both at the same path.
2. Request and Response
Route Handler functions receive a NextRequest object and must return a NextResponse. These are Next.js-extended versions of the standard Web Request and Response APIs.
NextResponse.json() is the most common way to send data back β it sets the Content-Type: application/json header and serializes your object automatically. You pass the data as the first argument and an options object (with status) as the second.
Common status codes
200 OK Β· 201 Created Β· 400 Bad Request Β· 401 Unauthorized Β· 404 Not Found Β· 500 Internal Server Error
NextResponse.json()
Accepts any serializable value as the first argument. Pass { status, headers } as the second argument to customize the HTTP response.
3. Reading Request Data
Route Handlers can read data from multiple places in the incoming request. The most common sources are the JSON body, URL search params, cookies, and headers.
cookies() and headers() imported from 'next/headers' are server-only functions. They can only be used inside Server Components, Route Handlers, and Server Actions β never in Client Components.
4. Server Actions
Route Handlers are great for external API consumers (mobile apps, third-party services). But when your own React components need to mutate data, Server Actions are often the better choice.
A Server Action is an async function marked with the "use server" directive at the top. Next.js automatically creates a secure POST endpoint behind the scenes and lets you call the function directly from Client Components or HTML forms β as if it were a regular function call.
Route Handler
Best for: external clients, REST APIs, webhooks, non-Next.js consumers. You call it with fetch().
Server Action
Best for: form submissions and mutations from your own React UI. Called like a function β no fetch() needed.
"use server" file never runs in the browser. Even if you import it in a Client Component, Next.js replaces the import with a secure RPC stub. Your database credentials, secrets, and logic stay on the server.
5. Form Handling with Server Actions
The most powerful use of Server Actions is wiring them directly to an HTML <form> via the action prop. When the user submits the form, Next.js calls your Server Action with the form's FormData β no onSubmit handler, no fetch(), and it works even if JavaScript is disabled.
This is called progressive enhancement: the form works as plain HTML, and JavaScript only adds the enhanced experience on top.
action attribute on a form normally accepts a URL string. Next.js overloads it to also accept a Server Action function reference. The framework handles the serialization, the POST request, and the response β all transparently.
6. revalidatePath
Next.js aggressively caches pages and data fetches. After a Server Action mutates data (adds a product, updates a cart, deletes an order), the cached pages still show the old data β until you explicitly invalidate them.
revalidatePath(path) clears the cache for a specific page path. On the next request to that path, Next.js re-runs the data fetching and serves fresh content.
mutates DB
clears cache
fetches fresh data
revalidatePath('/products') targets a specific URL. revalidateTag('products') targets all fetches tagged with a custom string β useful when the same data is used on multiple pages. For most CRUD mutations, revalidatePath is simpler.
Quiz
revalidatePath() do?You completed the API Routes & Server Actions quiz.
You just built a backend inside Next.js.
Now build a full-stack career that ships to production.
Join the Best AI Programs β three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses β