API Routes

Creating API Routes

API Routes let you create an API endpoint inside a Next.js app. You can do so by creating a function inside the pages/api directory that has the following format:

// req = request data, res = response data
export default (req, res) => {
  // ...
}

They can be deployed as Serverless Functions (also known as Lambdas).

Creating a simple API endpoint

Let’s try it out. Create a file called hello.js in pages/api with the following code:

export default (req, res) => {
  res.status(200).json({ text: 'Hello' })
}

Try accessing it at http://localhost:3000/api/hello. You should see {"text":"Hello"}. Note that:

That’s it! Before we wrap up this lesson, let’s talk about some tips for using API Routes on the next page.