In Next.js, custom API routes provide a way to create serverless functions that can be invoked on the server side. These functions allow you to handle server-side logic, fetch data, or perform other operations before rendering a page.
Serverless Functions: Custom API routes are essentially serverless functions. They allow you to define JavaScript functions in a special api directory within your Next.js project.
Backend Logic: Custom API routes are useful for handling backend logic.
Data Fetching: When a page is requested, you may need to fetch data before rendering the page. Instead of making these requests on the client side, you can use custom API routes to fetch data on the server side.
Security: Custom API routes are server-side, so you can use them to perform tasks that require secure processing.
File Structure: By organizing API routes in the api directory, Next.js provides a convention for structuring your project.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: ‘Hello, world!’ });
}
In this example, a custom API route is created at pages/api/hello.js, and when a request is made to this endpoint, it responds with a JSON object containing a simple greeting.