Create a Static REST Endpoint in Next.js

Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

We will learn how to create a REST endpoint that returns a hardcoded json response. Apart from that, we'll create deeply nested routes by following Next.js' file based router.

Instructor: [0:00] We're going to create an api folder inside the pages directory. Then we're going to create a greeting.js file inside of it. The next thing that we're going to do is to create a function, and we are going to call it handler, but you can call it whatever you want.

[0:17] This function accepts two parameters. The first one is the request object. It contains all the information about the request. For instance, the request header, the request body, the request method, etc. The second parameter is a response object, which has all the methods that we can use to respond back to the client.

[0:36] This API route will send back a JSON to the client. We call the JSON method from the response object. We said, "Agreed. Hello there."

[0:51] The last thing that we have to do is to explore the handler function as a default export. Let's make a GET request to localhost:3000/api/greeting, and we'll see that we get back the object that we have on the left.

[1:07] We will achieve the same if we have a greeting folder and if we rename this file to index.js. Let's send back the same request from last time and we get the same response back from the server. If we wanted to create a deeply nested route, we can keep adding folders here. Let's add a deeply folder. What we can do is to call the /api/greeting/deeply endpoint. I will get back the same response.

[1:39] To recap, in order to create an API route, we will have to create a folder called api inside the pages folder, and then start creating files inside of it. Each one of those files should have a function that accepts two parameters, the request object and the response object. Then, we will have to export that function as the default export for that file.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today