nextjs api example typescript

1. Install Next.js

First, you need to install Next.js in your project. You can do this by running the following command in your terminal:

npm install next

This will add Next.js as a dependency in your project.

2. Create an API Route

Next, you need to create an API route in your Next.js project. An API route is a serverless function that can handle HTTP requests. To create an API route, follow these steps:

  • Create a new file called api.ts (or any other name you prefer) inside the pages/api directory.
  • In the api.ts file, define a function that takes in a request and response object as parameters. This function will handle the HTTP request and send back a response. Here's an example:
import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  // Your code here
}

3. Implement the API logic

Inside the API route handler function, you can implement the logic for your API. This can include fetching data from a database, processing the request payload, or any other custom logic you need. Here's an example of how you can implement a simple API endpoint that returns a JSON response:

import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const data = {
    message: 'Hello, world!'
  };

  res.status(200).json(data);
}

In this example, the API route returns a JSON response with a message property set to "Hello, world!".

4. Test the API endpoint

To test the API endpoint you created, you can run your Next.js project and make a request to the API route. Next.js automatically sets up a development server that you can start by running the following command:

npm run dev

Once the development server is running, you can make a request to the API route by visiting http://localhost:3000/api in your browser or using a tool like cURL or Postman. You should see the JSON response returned by your API.

That's it! You have now created a basic API endpoint using Next.js with TypeScript. You can continue to build on this by adding more API routes and implementing more complex logic as needed.