Next js

API Routes In Next Js

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.js is accessible at /api/hello.


Creating a Simple API Route

Create a file:

js
// pages/api/hello.js

export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js API!' });
}

Request GET /api/hello will respond with JSON:

json
{ "message": "Hello from Next.js API!" }

Request Methods

You can handle different HTTP methods (GET, POST, etc.) by checking req.method.

Example:

js
export default function handler(req, res) {
if (req.method === 'POST') {
// Process POST request
res.status(200).json({ message: 'Data received' });
} else {
// Handle other methods or default
res.status(405).json({ error: 'Method not allowed' });
}
}

Accessing Request Data

  • Query parameters: req.query

  • Body data (POST, PUT): req.body (parsed automatically for JSON)

  • Headers: req.headers

Example:

js
export default function handler(req, res) {
const { name } = req.query;
res.status(200).json({ greeting: `Hello, ${name || 'Guest'}` });
}

Using API Routes with Frontend

You can fetch API routes like any other endpoint:

jsx
fetch('/api/hello')
.then((res) => res.json())
.then((data) => console.log(data));

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.

Leave a Reply

Your email address will not be published. Required fields are marked *