Create a Static REST Endpoint in Next.js

Share this video with your friends

Send Tweet
Published 7 months ago
Updated 6 months 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.