How to Build API in Next.js
Posted on
To build an API in Next.js, you can follow these steps:
Create a new Next.js app: Start by creating a new Next.js app using the create-next-app command. You can run this command in your terminal:
npx create-next-app my-app
Create an API route: Next.js provides a simple way to create API routes using the pages/api directory. Inside this directory, create a new file with a name that corresponds to the URL path of your API route. For example, if you want to create an API route at /api/hello, create a file called hello.js inside the pages/api directory.
Write your API logic: In the file you created in step 2, write the logic for your API route. You can use any Node.js libraries or frameworks that you like to handle requests and responses. Here's an example of a simple API route that returns a JSON response:
export default function handler(req, res) {
res.status(200).json({ message: 'Hello world!' });
}
Test your API: Start your Next.js app by running the npm run dev command, and then test your API by sending a request to the appropriate URL path. For example, if you created an API route at /api/hello, you can test it by sending a GET request to http://localhost:3000/api/hello.
Deploy your app: Once you've finished building your API, you can deploy your Next.js app to a hosting provider like Vercel or AWS. Make sure to follow the appropriate steps for your hosting provider to ensure that your API routes are properly configured and accessible.
That's it! With these steps, you should be able to create and deploy an API in Next.js.