---
title: "API Routes in Next.js"
url: https://khanwaseem.com/blog/course/api-routes-in-next-js
author: "khan Waseem"
published: 2026-11-22
updated: 2026-11-22
topics: ["course", "Nextjs Tutorial"]
description: "Build a backend inside your Next.js app with API routes and route handlers: request methods, dynamic routes, query strings, JSON bodies and error handling."
---

# API Routes in Next.js

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)[1. Your First API Route:](#1-your-first-api-route)
- [2. Route Handlers in the App Router:](#2-route-handlers-in-the-app-router)
- [3. Handling Different HTTP Methods:](#3-handling-different-http-methods)
- [4. Reading Query Strings:](#4-reading-query-strings)
- [5. Dynamic API Routes:](#5-dynamic-api-routes)
- [6. Calling Your API from a Page:](#6-calling-your-api-from-a-page)
- [7. Keeping Secrets Safe:](#7-keeping-secrets-safe)

- [Conclusion:](#conclusion)

## Introduction:

Next.js is not only a frontend framework. Every Next.js project can also hold its own backend: small server functions that receive an HTTP request and send back a response. These are called **API routes** (in the `pages` router) and **route handlers** (in the `app` router). They run only on the server, so you can safely talk to a database, call a third-party API with a secret key, or process a form, without building a separate Express server.

In this lesson we will create API routes, handle different HTTP methods, read query strings and JSON bodies, build dynamic API routes and call them from a page.

### 1. Your First API Route:

In the `pages` router, any file inside `pages/api` becomes an API endpoint instead of a page. The file exports a default function that receives a request (`req`) and a response (`res`) object.

```javascript
// pages/api/hello.js  ->  GET /api/hello
export default function handler(req, res) {
  res.status(200).json({ message: "Hello from Next.js!" });
}Code language: JavaScript (javascript)
```

Start the dev server with `npm run dev` and open `http://localhost:3000/api/hello`. You will see the JSON response in the browser:

```json
{ "message": "Hello from Next.js!" }Code language: JSON / JSON with Comments (json)
```

### 2. Route Handlers in the App Router:

If your project uses the `app` directory, API endpoints live in a file called `route.js` instead. You export one function for each HTTP method you want to support, and each function returns a standard Web `Response`.

```javascript
// app/api/hello/route.js  ->  GET /api/hello
export async function GET() {
  return Response.json({ message: "Hello from Next.js!" });
}Code language: JavaScript (javascript)
```

The idea is the same in both routers: the folder path becomes the URL, and the code runs on the server. The rest of this lesson shows both styles side by side.

### 3. Handling Different HTTP Methods:

A real API usually does more than one thing at the same URL. For example, `GET /api/todos` returns the list of todos and `POST /api/todos` creates a new one. In the `pages` router, check `req.method`:

```javascript
// pages/api/todos.js
let todos = [{ id: 1, title: "Learn Next.js", done: false }];

export default function handler(req, res) {
  if (req.method === "GET") {
    return res.status(200).json(todos);
  }

  if (req.method === "POST") {
    const { title } = req.body;
    if (!title) {
      return res.status(400).json({ error: "Title is required" });
    }
    const todo = { id: Date.now(), title, done: false };
    todos.push(todo);
    return res.status(201).json(todo);
  }

  res.setHeader("Allow", ["GET", "POST"]);
  res.status(405).json({ error: `Method ${req.method} not allowed` });
}Code language: JavaScript (javascript)
```

In the `app` router you simply export a separate function per method. Next.js answers other methods with `405 Method Not Allowed` for you.

```javascript
// app/api/todos/route.js
let todos = [{ id: 1, title: "Learn Next.js", done: false }];

export async function GET() {
  return Response.json(todos);
}

export async function POST(request) {
  const { title } = await request.json();
  if (!title) {
    return Response.json({ error: "Title is required" }, { status: 400 });
  }
  const todo = { id: Date.now(), title, done: false };
  todos.push(todo);
  return Response.json(todo, { status: 201 });
}Code language: JavaScript (javascript)
```

**Note:** the `todos` array here lives in server memory, so it resets whenever the server restarts. In a real app you would read and write a database instead.

### 4. Reading Query Strings:

Query strings such as `/api/search?q=react&limit=5` are useful for filtering and searching.

```javascript
// pages/api/search.js
export default function handler(req, res) {
  const { q = "", limit = "10" } = req.query;
  res.status(200).json({ query: q, limit: Number(limit) });
}Code language: JavaScript (javascript)
```

```javascript
// app/api/search/route.js
export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const q = searchParams.get("q") ?? "";
  const limit = Number(searchParams.get("limit") ?? 10);
  return Response.json({ query: q, limit });
}Code language: JavaScript (javascript)
```

### 5. Dynamic API Routes:

Just like pages, API routes can have dynamic segments written in square brackets. A file named `[id].js` matches `/api/users/1`, `/api/users/42` and so on.

```javascript
// pages/api/users/[id].js  ->  /api/users/:id
export default async function handler(req, res) {
  const { id } = req.query;
  const response = await fetch(`https://dummyjson.com/users/${id}`);

  if (!response.ok) {
    return res.status(404).json({ error: "User not found" });
  }

  const user = await response.json();
  res.status(200).json({ id: user.id, name: `${user.firstName} ${user.lastName}` });
}Code language: JavaScript (javascript)
```

In the `app` router the dynamic segment is a folder, and its value arrives in the second argument. From Next.js 15 onwards `params` is a Promise, so you `await` it:

```javascript
// app/api/users/[id]/route.js
export async function GET(request, { params }) {
  const { id } = await params;
  const response = await fetch(`https://dummyjson.com/users/${id}`);

  if (!response.ok) {
    return Response.json({ error: "User not found" }, { status: 404 });
  }

  const user = await response.json();
  return Response.json({ id: user.id, name: `${user.firstName} ${user.lastName}` });
}Code language: JavaScript (javascript)
```

### 6. Calling Your API from a Page:

Because the API lives in the same project, you call it with a relative URL from client components:

```javascript
"use client"
import { useEffect, useState } from "react";

export default function TodoList() {
  const [todos, setTodos] = useState([]);
  const [title, setTitle] = useState("");

  useEffect(() => {
    fetch("/api/todos").then((res) => res.json()).then(setTodos);
  }, []);

  const addTodo = async (e) => {
    e.preventDefault();
    const res = await fetch("/api/todos", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title }),
    });
    const todo = await res.json();
    setTodos((prev) => [...prev, todo]);
    setTitle("");
  };

  return (
    <form onSubmit={addTodo}>
      <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="New todo" />
      <button type="submit">Add</button>
      <ul>
        {todos.map((todo) => <li key={todo.id}>{todo.title}</li>)}
      </ul>
    </form>
  );
}Code language: JavaScript (javascript)
```

**Tip:** do not call your own API routes from `getStaticProps`, `getServerSideProps` or a Server Component. That code already runs on the server, so import the database or helper function directly instead of making an extra HTTP request to yourself.

### 7. Keeping Secrets Safe:

API routes are the right place for secret keys, because their code never reaches the browser. Put the key in `.env.local` and read it from `process.env`:

```php
# .env.local
WEATHER_API_KEY=your-secret-keyCode language: PHP (php)
```

```javascript
// app/api/weather/route.js
export async function GET() {
  const res = await fetch(
    `https://api.example.com/weather?city=Mumbai&key=${process.env.WEATHER_API_KEY}`
  );
  const data = await res.json();
  return Response.json({ temperature: data.temp });
}Code language: JavaScript (javascript)
```

Only variables that start with `NEXT_PUBLIC_` are sent to the browser. Anything else, like `WEATHER_API_KEY` above, stays on the server.

## Conclusion:

API routes turn your Next.js project into a full-stack application. You learned how to create endpoints in both the `pages` and `app` routers, handle `GET` and `POST`, read query strings and JSON bodies, build dynamic routes like `/api/users/[id]`, call your API from a component, and keep secrets on the server. In the next lesson we will look at Incremental Static Regeneration, which lets static pages stay fresh without a full rebuild.

### Related posts:

[React Redux](https://blog.khanwaseem.com/react-redux/)
[Incremental Static Regeneration (ISR) in Next.js](https://blog.khanwaseem.com/incremental-static-regeneration-isr-in-next-js/)
[What is Express? Building Web Applications with Node.js](https://blog.khanwaseem.com/what-is-express/)
[React Router](https://blog.khanwaseem.com/react-router/)

Powered by [YARPP](https://yarpp.com).
