DeployU
Interviews / Frontend Engineering / What are API routes and how do you use them in Next.js?

What are API routes and how do you use them in Next.js?

practical API Routes Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new feature that needs to have a simple backend API to store and retrieve data.

You could create a separate backend application, but this would be overkill for this simple use case.

The Challenge

Explain what API routes are in Next.js and how you would use them to solve this problem. What are the key benefits of using API routes?

Wrong Approach

A junior engineer might not be aware of API routes. They might try to solve this problem by creating a separate backend application, which would be a more complex and time-consuming solution.

Right Approach

A senior engineer would know that API routes are the perfect tool for this job. They would be able to explain what API routes are and how to use them to build a simple backend API.

Step 1: Understand What API Routes Are

API routes are a feature of Next.js that allows you to create a backend API inside your Next.js application.

Step 2: Create an API Route

To create an API route, you just need to create a new file in the pages/api directory.

Here’s how we can create a simple API route that returns a list of users:

// pages/api/users.js
export default function handler(req, res) {
  res.status(200).json([
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Doe' }
  ]);
}

This API route will be available at /api/users.

Dynamic API Routes

You can also create dynamic API routes. For example, the file pages/api/users/[id].js will be mapped to the /api/users/:id route.

// pages/api/users/[id].js
export default function handler(req, res) {
  const { id } = req.query;
  res.status(200).json({ id, name: `User ${id}` });
}

The Benefits of Using API Routes

BenefitDescription
SimplicityAPI routes are very easy to use.
IntegrationAPI routes are tightly integrated with the Next.js ecosystem.
ScalabilityAPI routes are serverless functions, which means that they can be scaled automatically.

Practice Question

You want to create a new API route that can handle `POST` requests. Which of the following would you use?