Create a New Next.js Application with an API Route

Lee Robinson
InstructorLee Robinson
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

Rather than using create-next-app, we can manually set up Next.js and create our first API route. This route allows you a straightforward solution for building an API alongside your React application with Next.js. No need to set up Express or any other Node.js server.

Lee Robinson: [0:00] To create a new Next.js application, we can run npx create-next-app, and then the name of our application. However, since I already have a application created, a folder setup, a git repository setup from the previous lesson, we're going to manually install Next.js rather than using npx. We can run npm i, we'll add react react-dom, as well as Next.

[0:33] Now, we can open up our package.json, and we'll see the new packages installed. Let's add a script, so that we can start up Next.js. Let's call this dev and it will use the Next command. The next step is to make a new top-level folder for pages. Inside of pages, we want to make a new file called Index.js.

[1:04] Now, this file is going to be the entry point into our application. Let's create a new function. That's the default export for this file. We're just going to make this return Hello World. Hit Save. Now, if we go down to our terminal, and we run our server, you'll see that it says it has started and it's available on port 3000.

[1:34] If we open up our browser, and we navigate to localhost:3000, we can see that it successfully worked, and we're able to see the first route in our application. Now, you'll also notice in our folder tree, we see .Next, which is the compiled code. We want to make sure that we add this to our gitignore, so that we don't commit this compiled code to GitHub.

[2:01] Let's also setup an API route. First, let's create a new folder inside pages for API. Then let's create a new API, hello.js. An API route is a straightforward way to create an API inside of Next.js. On your frontend, you have React, and on your backend, you have Node.js as an API route.

[2:26] Inside this file, we're going to export a default function called a handler that is going to take in a request and a response. This is going to allow us to create our API route. If we take the response, and let's do .status of a 200, and we want to return some JSON of name, and my name is Lee.

[2:58] If we save this, and we navigate back to our browser, we go to localhost/api/hello, we will see the JSON response from our API route. If we open up DevTools, and we go to the Network tab, we also see this status come through. It was originally a 200, we're seeing a 304 here for not modified. If I do a hard refresh, I'm able to see that 200.