What are API Routes?
Next.js API routes allow you to build RESTful endpoints inside your Next.js project.
Example:
Create /pages/api/hello.js:
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js API' })
}
Visit /api/hello to see the JSON response.
Use Cases
- Handling form submissions.
- CRUD operations.
- Authentication and server-side logic.
API routes integrate seamlessly with frontend pages and can access environment variables securely.