API routes in Next.js allow you to handle backend logic within your application, making it easy to build full-stack applications. To effectively use API routes, you need to understand how to handle requests and responses. In this article, we’ll explore how to handle different types of requests, send responses, and manage errors in Next.js API routes.
Handling Requests
In Next.js API routes, the req object contains information about the incoming request, such as the HTTP method, headers, query parameters, and body. You can use this information to determine how to handle the request.
Handling Different HTTP Methods
You can handle different HTTP methods, such as GET, POST, PUT, and DELETE, by checking the req.method property. Here’s an example:
// pages/api/user.js
export default function handler(req, res) {
if (req.method === 'GET') {
// Handle GET request
res.status(200).json({ name: 'John Doe' });
} else if (req.method === 'POST') {
// Handle POST request
const { name } = req.body;
res.status(201).json({ message: `User ${name} created` });
} else {
// Handle other HTTP methods
res.status(405).json({ message: 'Method not allowed' });
}
}
In this example, the API route handles GET and POST requests differently.
Accessing Query Parameters
You can access query parameters from the req.query object. For example, to handle a request with a query parameter like /api/user?id=1, you can use the following code:
// pages/api/user.js
export default function handler(req, res) {
const { id } = req.query;
res.status(200).json({ id });
}
Accessing Request Body
For POST, PUT, and PATCH requests, you can access the request body from the req.body object. Here’s an example:
// pages/api/user.js
export default function handler(req, res) {
if (req.method === 'POST') {
const { name, email } = req.body;
res.status(201).json({ name, email });
} else {
res.status(405).json({ message: 'Method not allowed' });
}
}
Sending Responses
In Next.js API routes, the res object is used to send a response back to the client. You can send different types of responses, such as JSON, text, or even files.
Sending JSON Responses
To send a JSON response, use the res.json() method. Here’s an example:
// pages/api/user.js
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' });
}
Sending Text Responses
To send a text response, use the res.send() method. Here’s an example:
// pages/api/user.js
export default function handler(req, res) {
res.status(200).send('Hello, world!');
}
Sending File Responses
To send a file as a response, use the res.sendFile() method. Here’s an example:
// pages/api/file.js
import { join } from 'path';
export default function handler(req, res) {
const filePath = join(process.cwd(), 'public', 'example.pdf');
res.sendFile(filePath);
}
Handling Errors
It’s important to handle errors gracefully in API routes. You can use the res.status() method to send an appropriate status code and error message. Here’s an example:
// pages/api/user.js
export default function handler(req, res) {
if (req.method !== 'GET') {
res.status(405).json({ message: 'Method not allowed' });
return;
}
try {
// Handle the request
res.status(200).json({ name: 'John Doe' });
} catch (error) {
res.status(500).json({ message: 'Internal server error' });
}
}
Secrets and Hidden Facts
- Middleware: Use middleware to handle tasks like authentication, logging, or error handling in API routes.
- Environment Variables: Use environment variables to store sensitive information, such as database credentials or API keys.
- Rate Limiting: Implement rate limiting to prevent abuse of your API routes.
Conclusion
Handling requests and responses in Next.js API routes is a fundamental skill for building full-stack applications. Whether you’re handling different HTTP methods, sending responses, or managing errors, Next.js provides the tools and flexibility you need to create robust and scalable applications.
Reviewed by Curious Explorer
on
Friday, February 28, 2025
Rating:

No comments: