API Routes in Next.js

In Next.js, API Routes let you create backend endpoints directly within your app, allowing you to build full-stack features without a separate server.

🧠 How API Routes Work:

  • API routes are defined inside the /pages/api directory.
  • Each file in this folder maps to a corresponding API endpoint.

Example of an API Route:

javascript
1// pages/api/hello.js 2export default function handler(req, res) { 3 res.status(200).json({ message: 'Hello, World!' }); 4}
  • This file defines the endpoint /api/hello which responds with a simple JSON object.
  • API routes support different HTTP methods like GET, POST, PUT, and DELETE, enabling flexible server-side logic.

In short:

  • API Routes let you run server-side code (e.g., handling requests, accessing databases).
  • They’re great for adding dynamic backend features directly into your Next.js project.