What Are API Routes?
-
API Routes let you create serverless API endpoints inside your Next.js app.
-
They live in the
pages/api/directory. -
Each file corresponds to an endpoint — e.g.,
pages/api/hello.jsis accessible at/api/hello.
Creating a Simple API Route
Create a file:
Request GET /api/hello will respond with JSON:
Request Methods
You can handle different HTTP methods (GET, POST, etc.) by checking req.method.
Example:
Accessing Request Data
-
Query parameters:
req.query -
Body data (POST, PUT):
req.body(parsed automatically for JSON) -
Headers:
req.headers
Example:
Using API Routes with Frontend
You can fetch API routes like any other endpoint:
When to Use API Routes
-
Handle form submissions.
-
Authenticate users.
-
Connect to databases.
-
Fetch or process external data.
-
Create backend logic in your Next.js app without separate server.
Summary
| Feature | Description |
|---|---|
| Location | Files inside pages/api/ |
| Endpoint URL | Matches file path, e.g. /api/hello |
| Request Methods | Handle GET, POST, etc., via req.method |
| Request Data | Access via req.query, req.body, req.headers |
| Response | Use res.status(), res.json(), etc. |
