Next.js API Routes provide a powerful way to build backend functionality directly within your Next.js application. This means you can create server-side logic for tasks like data fetching and data mutations without needing to set up a separate backend server. This chapter explores how to leverage API Routes for these common backend operations.
API Routes live in the pages/api directory. Each file in this directory becomes an API endpoint. For example, pages/api/users.js will be accessible at /api/users.
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' });
}The handler function in an API Route receives two arguments: req (the incoming request object) and res (the server response object). You use res to send data back to the client.
One common use case is to expose data from an external API or a database through your API Routes. This allows your frontend to interact with a unified API layer, abstracting away the complexities of where the data actually resides.
Let's imagine we have a pages/api/posts.js file that fetches data from a hypothetical external API. We'll handle GET requests to retrieve a list of posts.
import fetch from 'node-fetch';
export default async function handler(req, res) {
if (req.method === 'GET') {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
res.status(200).json(posts);
} catch (error) {
res.status(500).json({ message: 'Error fetching posts', error: error.message });
}
} else {
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}In this example:
- We use
node-fetch(you might need to install this:npm install node-fetchoryarn add node-fetch) to make HTTP requests. - We check
req.methodto ensure we only handleGETrequests. - We fetch data from
jsonplaceholder.typicode.com. - We send the fetched
postsback to the client with a200status code. - Error handling is included to catch potential network issues.