As you start building API routes in Next.js, you'll quickly realize that your backend functionality often needs to receive data from the client. This data can arrive in various forms: query parameters in the URL, data sent in the request body, or even custom information within request headers. Understanding how to access and utilize this information is crucial for creating dynamic and interactive API endpoints.
In Next.js API routes, the req object (the incoming message object) provides access to all the request data. Let's break down how to access each type of data.
Query parameters are key-value pairs appended to the end of a URL, typically after a question mark (?). They are commonly used for filtering, sorting, or pagination of data. In your API route handler, you can access them via req.query.
export default function handler(req, res) {
const { searchTerm, page } = req.query;
console.log('Search Term:', searchTerm);
console.log('Page:', page);
res.status(200).json({ message: `Searching for ${searchTerm} on page ${page}` });
}For example, if a request is made to /api/search?searchTerm=nextjs&page=2, req.query.searchTerm would be 'nextjs' and req.query.page would be '2'.
When you need to send larger amounts of data to your API, such as creating a new resource or updating an existing one, you'll typically use the request body. This is common with HTTP methods like POST, PUT, and PATCH. Next.js automatically parses JSON request bodies for you. You can access this data through req.body.
export default function handler(req, res) {
if (req.method === 'POST') {
const { name, email } = req.body;
console.log('Received data:', { name, email });
res.status(201).json({ message: `User ${name} created successfully!` });
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}