Creating API Functions in Next.js

Next.js offers built-in support for API routes, allowing you to create server-side functions as part of your application. These API functions run on the server and are ideal for handling backend tasks such as database operations, authentication, or third-party integrations. In this article, we’ll explore how to create and use API routes in Next.js.

1. What Are API Routes?

API routes in Next.js are JavaScript or TypeScript files inside the /pages/api directory. Each file in this directory maps to an endpoint, and the default export of the file is the request handler function. These routes are server-side only, ensuring that sensitive logic is kept secure.

2. Setting Up a Simple API Route

Example: Hello World API

Create a file named hello.js in the /pages/api directory:

// /pages/api/hello.js

export default function handler(req, res) {

 res.status(200).json({ message: ‘Hello, World!’ });

}

Now, navigate to http://localhost:3000/api/hello in your browser, and you’ll see:

{
  "message": "Hello, World!"
}

3. Handling HTTP Methods

API routes can handle different HTTP methods (GET, POST, PUNow, navigate to http://localhost:3000/api/hello in your browser, and you’ll see:

{

 “message”: “Hello, World!”

}

T, DELETE, etc.) based on the req.method property.

Example: Handling Multiple Methods

// /pages/api/user.js

export default function handler(req, res) {

 if (req.method === ‘GET’) {

  res.status(200).json({ message: ‘This is a GET request’ });

 } else if (req.method === ‘POST’) {

  const data = req.body;

  res.status(201).json({ message: ‘Data received’, data });

 } else {

  res.setHeader(‘Allow’, [‘GET’, ‘POST’]);

  res.status(405).end(`Method ${req.method} Not Allowed`);

 }

}

  • A GET request to /api/user will return a message.
  • A POST request to /api/user will return the data sent in the request body.
  • Any other HTTP method will return a 405 status code.

4. Parsing Request Data

Next.js automatically parses JSON data sent in the request body. To handle other formats like form-data, you can use libraries such as multer or formidable.

Leave a comment

Your email address will not be published. Required fields are marked *