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 Example
Products API β€” backend without a separate server

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.

App Router API File Convention
app/api/
folder = URL prefix
β†’
products/
subfolder = path segment
β†’
route.ts
export GET, POST…
app/ β”œβ”€β”€ api/ β”‚ β”œβ”€β”€ products/ β”‚ β”‚ β”œβ”€β”€ route.ts ← /api/products β”‚ β”‚ └── [id]/ β”‚ β”‚ └── route.ts ← /api/products/42 β”‚ └── cart/ β”‚ └── route.ts ← /api/cart β”œβ”€β”€ products/ β”‚ └── page.tsx ← UI page (not an API) └── layout.tsx
Convention: The filename must be exactly 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.

app/api/products/route.ts GET and POST handlers
curl output
$ curl http://localhost:3000/api/products [{"id":1,"name":"Wireless Headphones","price":49.99,"category":"Electronics"}, {"id":2,"name":"USB-C Hub","price":29.99,"category":"Electronics"}, {"id":3,"name":"Laptop Stand","price":39.99,"category":"Accessories"}, {"id":4,"name":"Mechanical Keyboard","price":89.99,"category":"Electronics"}, {"id":5,"name":"Desk Lamp","price":24.99,"category":"Accessories"}] $ curl -X POST http://localhost:3000/api/products \ -H "Content-Type: application/json" \ -d '{"name":"Smart Watch","price":199.99,"category":"Electronics"}' {"id":6,"name":"Smart Watch","price":199.99,"category":"Electronics"}
πŸ“₯

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.

app/api/products/[id]/route.ts Dynamic segment β€” GET, PATCH, DELETE
app/api/products/route.ts Reading search params, cookies, headers
Note: 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.

app/actions/cart.ts Server Action β€” add to cart
Security model: Code inside a "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.

app/actions/products.ts Server Action reading FormData
app/admin/new-product/page.tsx Form component β€” no onSubmit, no fetch()
Why no onSubmit? The HTML 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.

app/actions/products.ts revalidatePath after mutations
revalidatePath Flow
Server Action
mutates DB
β†’
revalidatePath('/products')
clears cache
β†’
Next request to /products
fetches fresh data
revalidatePath vs revalidateTag: 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.

7. cookies() and headers()

Server Actions run on the server, so they have full access to HTTP cookies and request headers β€” exactly like Route Handlers. The cookies() function from 'next/headers' returns a mutable cookie store: you can both read and set cookies inside Server Actions.

app/actions/auth.ts Reading and setting auth cookies in Server Actions
curl output β€” authenticated route
$ curl http://localhost:3000/api/products \ --cookie "auth_token=jwt.token.here" {"data":[{"id":1,"name":"Wireless Headphones",...}],"page":1,"total":5} $ curl http://localhost:3000/api/products {"error":"Unauthorized"}
app/api/products/route.ts Reading headers in a Route Handler
Cookie security tip: Always set httpOnly: true for auth cookies. This prevents JavaScript on the page from reading the cookie β€” critical for protection against XSS attacks. The secure: true flag ensures the cookie is only sent over HTTPS in production.

Quiz

Question 1 of 5
Where do you create an API route in Next.js App Router?
Question 2 of 5
What directive marks a Server Action?
Question 3 of 5
What does revalidatePath() do?
Question 4 of 5
What is the main advantage of Server Actions over regular API routes for forms?
Question 5 of 5
How do you send a JSON response from a Route Handler?
0
/ 5
Great job!

You completed the API Routes & Server Actions quiz.

Next Lesson

Deployment & Production β†’
Arc E continues β€” take your Next.js app live on Vercel and configure production environments.
Africa & India's Best AI Academy
πŸ€– AI-first πŸŽ“ Placement Assistance

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 β†’