API routes
- React course
- Advanced
- Lesson 9/56
- 4 min
Learn to write route handlers in Next.js.
API routes
In Next.js App Router, API routes are defined in app/api/... as route.js files. Each file exports functions that handle HTTP requests.
For example, app/api/hello/route.js answers /api/hello. You write separate functions for GET, POST, PUT, DELETE.
API routes run on the server; no JavaScript is sent to the client.
HTTP methods
You write a separate exported function per HTTP method: export async function GET(request), export async function POST(request) and so on. Next.js runs the matching function based on the request method.
Undefined methods return 405. This is the standard REST API approach.
Functions should be async because they usually wait on a database or external API.
Practice First API route
Write a GET function: take request as parameter, return new Response("Hello API"). The function must be async and exported.
Starter code
// app/api/hello/route.js
// GET fonksiyonunu buraya yazSample solution
// app/api/hello/route.js
export async function GET(request) {
return new Response("Hello API");
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which file defines an API route?
- route.js Correct answer
- page.js
- api.js
- server.js
Explanation: app/api/.../route.js is the API route.
2 GET function
export async function ____(request) {
return new Response("Merhaba");
}
export async function GET(request) {
return new Response("Merhaba");
}
Explanation: The GET function handles GET requests.
3 API routes: match the terms
| Term | Meaning |
|---|---|
route.js |
API file |
GET |
Read |
POST |
Write |
DELETE |
Delete |