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`);
}
}You can also create dynamic API routes by using bracket notation in the file name, similar to dynamic routes in the pages directory. For instance, pages/api/users/[id].js would match requests like /api/users/123.
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const { id } = req.query;
res.status(200).json({ userId: id });
}The req.query object contains parameters from the URL. For dynamic routes, this will include the bracketed parameters. For query strings in GET requests (e.g., /api/items?category=electronics), these will also be available in req.query.
API Routes are deployed as serverless functions on platforms like Vercel, Netlify, or AWS Lambda. This means they scale automatically with your traffic and you only pay for the compute time you consume. This is a significant advantage for building cost-effective and scalable applications.
graph TD;
A[Client Request] --> B{Next.js App};
B --> C[pages/api Folder];
C --> D[API Route Handler];
D --> E[Database/Third-Party API];
E --> D;
D --> B;
B --> A;
subgraph Serverless Deployment
C
D
E
end
In summary, Next.js API Routes offer a streamlined way to build backend capabilities within your Next.js applications. By placing your API endpoints in the pages/api directory, you can leverage serverless functions for data fetching, mutations, and integrating with external services, all while keeping your frontend and backend logic cohesive.