Create an API Route in Next.js

July 25, 2019 0 Comments

Create an API Route in Next.js

 

 

Instructor: 00:00 We'll start by NPM installing next, hop into our project, create a pages/index.js, and then export a default function. This will have a div, just as "Hello." Then we can go ahead and run npx next, which will invoke next and target that index.js, and go to localhost3000 in our browser.

00:27 You can see Hello here represented by this div with "Hello" in it. To use an API route, to create an API, we'll go into our pages directory, create a directory called "API." Inside of that directory, create a file called "hello.js." Inside of here, we can just export the default function, which takes a request and response.

00:47 There, we'll just response JSON. You'll have an object with a message of "hello" on it.

00:53 To access this response inside of this file, let's go ahead and set up that functionality inside our index.js. We'll go ahead and use a useState hook. Import useState from React and we'll just grab a value and the value setter from the useState. We'll just start it with an object with a message of waiting for message.

01:22 Drop that message inside of our div. We'll just put that right here and say value.message. Let's save and we should see, "Waiting for message." We'll make this a bit bigger.

01:36 Now we can go ahead and fetch our value. To fetch our value, we'll setup a function called fetchValue, which will take the event. That'll be a click event on the button below. Inside of here, we're going to fetch/api/hello, which directly mirrors the API hello directory structure.

01:57 I want to await this. This needs to be an async function. We'll get the response off of that fetch. We can just use that setValue setter and it was await the response.json. Since this will go ahead and parse the response as JSON.

02:14 All we have to do now is invoke this fetch value, which we can do with a button. Button, we'll say fetchValue and onClick, we'll pass in our fetchValue function. Let's save here. When we click on this button, we'll get hello back.

02:32 Because this is node, it opens up a whole world of possibility such as creating a file. We'll call this data.json. Inside of our JSON file, we'll have a message. The message can just be from json file.

02:48 Now, because this is Node, we can just go ahead and import the file. We'll say, "data from," and we'll go up the directories necessary to get to our data.json file. Now, just response.json with the contents of that file. Now, when I refresh here and click fetch value, you can see that we got from json file.

03:11 You could install any Node packages or any heavy dependencies for image processing or language detection or anything inside of here, use it in Node, and still keep your front end lightweight and decoupled from the back end features.


Tag cloud