
Api Routes in NextJS
In Next.js, API routes allow you to build backend functionality within your application. These routes run on the server and can handle requests like REST APIs.
📌 Creating an API Route
API routes are placed inside the pages/api/
directory. Each file inside this directory is mapped to /api/<filename>
.
🔹 Basic Example
Create pages/api/hello.js
:
export default function handler(req, res) { if (req.method === "GET") { res.status(200).json({ message: "Fetching user data" }); } else if (req.method === "POST") { res.status(201).json({ message: "User created" }); } else { res.setHeader("Allow", ["GET", "POST"]); res.status(405).end(`Method ${req.method} Not Allowed`); }}
GET /api/user
→ Returns "Fetching user data"POST /api/user
→ Returns "User created"Other methods → Returns
405 Method Not Allowed
📌 Using Query Parameters
🔹 Example: Get User by ID
Create pages/api/user/[id].js
:
export default function handler(req, res) { if (req.method === "POST") { const { name, email } = req.body; res.status(201).json({ message: `User ${name} with email ${email} created` }); } else { res.status(405).json({ message: "Method Not Allowed" }); }}
Send a
POST
request with JSON body{ "name": "John", "email": "john@example.com" }
Response:
{ "message": "User John with email john@example.com created" }
📌 Connecting to a Database
Next.js API routes work well with databases like PostgreSQL, MongoDB, or Firebase.
🔹 Example: Fetch Data from PostgreSQL
Using pg
for PostgreSQL:
import { Pool } from "pg";const pool = new Pool({ user: "your_user", host: "localhost", database: "your_db", password: "your_password", port: 5432,});export default async function handler(req, res) { if (req.method === "GET") { const { rows } = await pool.query("SELECT * FROM users"); res.status(200).json(rows); } else { res.status(405).json({ message: "Method Not Allowed" }); }}
GET /api/users
→ Returns users from PostgreSQL.
📌 Middleware in API Routes
Middleware can be used for authentication, logging, etc.
🔹 Example: Authentication Middleware
export function withAuth(handler) { return async (req, res) => { const token = req.headers.authorization; if (!token || token !== "your-secret-token") { return res.status(401).json({ message: "Unauthorized" }); } return handler(req, res); };}// Apply to an API routeexport default withAuth(async function handler(req, res) { res.status(200).json({ message: "Authenticated request" });});
📌 When to Use API Routes?
✅ When you need server-side logic (e.g., fetching data from a database).
✅ When handling form submissions.
✅ When interacting with third-party APIs securely.
❌ Not recommended for real-time updates (use WebSockets or Next.js Edge Functions).