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
Once the new project is created, you should have something like this when you open up your project๐๐ป
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๐๐ป
It's time to throw the boring stuff in the trash
Let's create our first endpoint, which is going to be a GET request. First, we need to import some things from next/server
๐๐ป
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๐๐ป
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๐๐ป
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๐๐ป
Now, let's try making a POST request in postman/Thunderclient. The result should be something like this๐๐ป
Awesome work! You now know the basics of creating endpoints in nextjs
Top comments (0)