API Routes

API routes provide a solution to build your API with Next.js.

Overview

API routes are a feature in Next.js that allow you to build serverless APIs with ease. They are server-side JavaScript functions that respond to HTTP requests, and they can be used to fetch and manipulate data from databases, external APIs, or other data sources.

How to use

Here we use API Routes. The installation method is as follows below.

Step 1: Create the API Route

To create an API route in Next.js, you need to create a file under the pages/api directory. The file should be named after the API endpoint that you want to create, and it should export a default async function that handles the request.

For example, let's create an API route called hello that returns a JSON response with a message

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  res.status(200).json({ message: 'Hello world!' });
}

Step 2: Use the API Route

Now that you have created the API route, you can use it in your application. You can call the API route from any component using the fetch API or any other library that makes HTTP requests.

For example, let's create a simple component that fetches the hello API and displays the message:

components/Hello.tsx
import { useState } from 'react';

export const Hello = () => {
  const [message, setMessage] = useState('');

  const handleClick = async () => {
    const response = await fetch('/api/hello');
    const data = await response.json();
    setMessage(data.message);
  };

  return (
    <div>
      <p>{message}</p>
      <button onClick={handleClick}>Say hello</button>
    </div>
  );
};

Step 3: Add TypeScript Types

To add TypeScript types to your API routes, you can create a separate TypeScript definition file for each API endpoint. The definition file should have the same name as the API route file, but with a .d.ts extension.

For example, let's create a definition file for the hello API:

pages/api/hello.d.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<{ message: string }>,
): Promise<void>;

In this example, we are defining the types of the req and res objects, as well as the type of the response body.

Last updated