Welcome to the exciting world of API Routes in Next.js! This powerful feature allows you to build backend functionality directly within your Next.js application. Imagine creating a full-stack application where your serverless functions live alongside your frontend code. That's the magic of API Routes.
Traditionally, building a full-stack application meant setting up a separate backend server, managing its deployment, and handling communication between your frontend and backend. Next.js simplifies this by enabling you to create API endpoints as serverless functions within your project. This means you can handle tasks like fetching data from databases, processing form submissions, integrating with third-party APIs, and much more, all without leaving your Next.js project.
API Routes reside in the pages/api directory of your Next.js project. Any file within this directory automatically becomes an API endpoint. For example, a file named pages/api/hello.js will be accessible at /api/hello.
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ message: 'Hello from the API!' });
}The core of an API Route is an exported default function. This function receives two arguments: req (an instance of http.IncomingMessage with additional properties provided by Next.js) and res (an instance of http.ServerResponse with additional properties). You use these objects to handle incoming requests and send back responses.
HTTP methods like GET, POST, PUT, DELETE, and others are automatically handled by your API Route. You can conditionally execute logic based on the request method using req.method.
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
// Handle GET request
res.status(200).json({ data: 'This is a GET response' });
} else if (req.method === 'POST') {
// Handle POST request
const { name } = req.body;
res.status(201).json({ message: `Hello, ${name}!` });
} else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}