DEV Community

Jahkamso
Jahkamso

Posted on

Create Api Endpoint in Next.js

I recently learned I could create an api endpoint in nextjs without having to use node/express. I'll share my little knowledge on what I've learned and how you can start creating api endpoints in nextjs.

First you need to initialise a next app

nextjs setup command

nextjs setup options

Once the new project is created, you should have something like this when you open up your projectπŸ‘‡πŸ»

Image description

Now, it's time to create some folders (nextjs uses folders for routing). Create 2 folders inside the app folder with a new file called hello.js. It should look something like thisπŸ‘‡πŸ»

Image description

It's time to throw the boring stuff in the trash

trash throw gif

Let's create our first endpoint, which is going to be a GET request. First, we need to import some things from next/serverπŸ‘‡πŸ»

Image description

This 2 imports we've made are basically telling nextjs that we want to be able to send a response and make a request, similarly to the request and response argument in nodejs.

Now, let's create a simple function for our GET request. Here's how you do itπŸ‘‡πŸ»

Image description

To test if this works, start your project by typing npm run dev in the terminal. Now, head over to postman or use an extension in vscode called Thunderclient, and then add this url http://localhost:3000/api/endpoints.

You should have something like thisπŸ‘‡πŸ»

nextjs get request thunderclient

Great! Now we've successfully created a GET request, now what? Well, now it's time to learn how to create a POST request to be able to get information from users on the frontend.

To do this, we basically repeat the same thing but with some little tweaks as shown belowπŸ‘‡πŸ»

nextjs get request thunderclient

Now, let's try making a POST request in postman/Thunderclient. The result should be something like thisπŸ‘‡πŸ»

Image description

Awesome work! You now know the basics of creating endpoints in nextjs

clapping gif

Top comments (0)