Next.js goes beyond just building user interfaces; it empowers you to create server-side functionality directly within your project using API Routes. This means you can build full-stack applications without needing a separate backend server. Think of API Routes as serverless functions baked into your Next.js application.
To get started, you'll need to create a new directory within your pages folder named api. Any file you place inside this pages/api directory will automatically be treated as an API endpoint.
graph TD; pages --> api;
Let's create our very first API Route. Inside the pages/api directory, create a new file called hello.js. This file will correspond to the /api/hello endpoint on your Next.js server.
export default function handler(req, res) {
res.status(200).json({ text: 'Hello from Next.js API!' });
}Let's break down what's happening in this hello.js file:
export default function handler(req, res): This is the core of your API Route. It's a default exported function that Next.js will execute when the/api/helloendpoint is hit.req(request): This object contains information about the incoming request, such as query parameters, headers, and the request body.res(response): This object is used to send a response back to the client. You can set the status code, headers, and the response body.
res.status(200): This sets the HTTP status code of the response to 200 (OK), indicating that the request was successful..json({ text: 'Hello from Next.js API!' }): This sends a JSON response back to the client with a simple message.
Now, if you run your Next.js development server (usually with npm run dev or yarn dev), you can visit http://localhost:3000/api/hello in your browser. You should see the following JSON output: