Blog>
Snippets

Using the API Routes

Set up an API route in the pages/api directory and create a simple handler function that sends a JSON response.
// pages/api/hello.js
export default function handler(req, res) {
  // Sends a JSON response with a message
  res.status(200).json({ message: 'Hello from the API!' });
}
This code sets up a new API route at pages/api/hello.js. When this endpoint is accessed with a GET request, it responds with a JSON object containing a greeting message.