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`);
}
}If a POST request is sent to /api/users with a JSON body like { "name": "Alice", "email": "alice@example.com" }, then req.body.name would be 'Alice' and req.body.email would be 'alice@example.com'.
HTTP headers provide metadata about the request, such as the content type, authentication tokens, or custom information your application might need. You can access them via req.headers.
export default function handler(req, res) {
const authHeader = req.headers['authorization'];
const contentType = req.headers['content-type'];
console.log('Authorization Header:', authHeader);
console.log('Content-Type Header:', contentType);
if (authHeader === 'Bearer my-secret-token') {
res.status(200).json({ message: 'Authenticated successfully!' });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
}In this example, if the request included an Authorization: Bearer my-secret-token header, req.headers['authorization'] would be 'Bearer my-secret-token'.
It's important to note that header names are typically case-insensitive. While the example uses lowercase, req.headers['Authorization'] would also work.
graph TD
Client -->|GET /api/items?filter=active| Server
Server -->|req.query.filter| API_Route_Handler
API_Route_Handler -->|Processed Data| Server
Server -->|200 OK {items}| Client
Client -->|POST /api/users { "name": "Bob" }| Server
Server -->|req.body.name| API_Route_Handler
API_Route_Handler -->|Processed Data| Server
Server -->|201 Created {user}| Client
Client -->|GET /api/resource Header: X-Custom: value| Server
Server -->|req.headers['x-custom']| API_Route_Handler
API_Route_Handler -->|Processed Data| Server
Server -->|200 OK| Client
By mastering how to access query parameters, request bodies, and headers, you gain the power to build robust and versatile API routes that can handle a wide range of client interactions and data exchanges within your Next.js application.