Next.js - API Routes
API routes in Next.js allow for the creation of server-side endpoints within the pages/api
directory, enabling developers to implement server-side logic and handle requests from client-side code.
1. Creating API Routes
To create an API route in Next.js, simply create a file within the pages/api
directory with the desired endpoint name. The file exports a default function handler that receives req
and res
objects representing the request and response, respectively.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js API' });
}
In this example, a simple API route named hello
is created, which responds with a JSON object containing a greeting message.
2. Handling Requests
API routes in Next.js allow for the handling of various types of HTTP requests, including GET, POST, PUT, DELETE, etc. Developers can implement custom logic within the handler function to process incoming requests and generate appropriate responses.
// pages/api/users.js
export default function handler(req, res) {
if (req.method === 'GET') {
// Logic to handle GET request
res.status(200).json({ message: 'GET request received' });
} else if (req.method === 'POST') {
// Logic to handle POST request
res.status(200).json({ message: 'POST request received' });
} else {
res.status(405).json({ message: 'Method Not Allowed' });
}
}
In this example, an API route named users
is created to handle both GET and POST requests. Depending on the request method, the appropriate logic is executed to generate the response.
3. Accessing Query Parameters
API routes in Next.js allow for the extraction of query parameters from the request URL, enabling developers to implement dynamic functionality based on user input.
// pages/api/product/[id].js
export default function handler(req, res) {
const { id } = req.query;
// Logic to fetch product data based on id
res.status(200).json({ productId: id });
}
In this example, an API route named product/[id]
is created to handle requests for retrieving product data based on the provided id
query parameter.
4. Error Handling
Next.js provides built-in error handling capabilities for API routes, allowing developers to gracefully handle errors that occur during request processing.
// pages/api/error.js
export default function handler(req, res) {
try {
// Logic that may throw an error
throw new Error('An error occurred');
} catch (error) {
res.status(500).json({ message: error.message });
}
}
In this example, an API route named error
is created to demonstrate error handling. Any errors thrown within the handler function are caught and returned as a JSON response with an appropriate status code.
Conclusion
API routes in Next.js provide a powerful mechanism for implementing server-side logic and handling HTTP requests from client-side code. With support for various request methods, query parameters, and error handling, developers can build robust and scalable APIs within their Next.js applications.
Comments
Post a Comment