How to Create API Route in Next.js: Simple Guide
In Next.js, create an API route by adding a JavaScript or TypeScript file inside the
pages/api folder. Export a default function that receives req and res objects to handle HTTP requests and send responses.Syntax
To create an API route in Next.js, place a file inside the pages/api directory. The file name becomes the API endpoint path. Export a default function that takes req (request) and res (response) parameters to handle incoming requests.
req: Contains request data like method, headers, and body.res: Used to send back status and data to the client.
javascript
export default function handler(req, res) { // Your code here res.status(200).json({ message: 'Hello from API' }) }
Example
This example creates a simple API route at /api/hello that responds with a JSON message. It shows how to check the HTTP method and send a JSON response.
javascript
export default function handler(req, res) { if (req.method === 'GET') { res.status(200).json({ message: 'Hello, Next.js API!' }) } else { res.status(405).json({ error: 'Method Not Allowed' }) } }
Output
{"message":"Hello, Next.js API!"}
Common Pitfalls
Common mistakes when creating API routes include:
- Placing API files outside the
pages/apifolder, so Next.js does not recognize them as API routes. - Not exporting a default function, which is required for the route to work.
- Forgetting to handle HTTP methods properly, causing unexpected errors.
- Not sending a response with
res.status().json()or similar, leaving the request hanging.
javascript
/* Wrong: API file outside pages/api folder */ // This will NOT work as an API route export default function handler(req, res) { res.status(200).json({ message: 'Wrong location' }) } /* Right: Inside pages/api/hello.js */ export default function handler(req, res) { res.status(200).json({ message: 'Correct API route' }) }
Quick Reference
Summary tips for creating Next.js API routes:
| Step | Description |
|---|---|
| 1 | Create a file inside pages/api folder |
| 2 | Export a default function with (req, res) parameters |
| 3 | Use req.method to handle HTTP methods |
| 4 | Send response with res.status().json() or similar |
| 5 | Access your API at /api/filename URL |
Key Takeaways
Place API route files inside the pages/api folder to create endpoints.
Export a default function that receives req and res to handle requests.
Always send a response to avoid hanging requests.
Check req.method to handle different HTTP methods properly.
Access your API routes via /api/filename URL in your Next.js app.