Lesson 13 of 15 · 4 min

API Routes in Next.js

Build a backend inside your Next.js app with API routes and route handlers: request methods, dynamic routes, query strings, JSON bodies and error…

On this page
  1. Introduction:
  2. 1. Your First API Route:
  3. 2. Route Handlers in the App Router:
  4. 3. Handling Different HTTP Methods:
  5. 4. Reading Query Strings:
  6. 5. Dynamic API Routes:
  7. 6. Calling Your API from a Page:
  8. 7. Keeping Secrets Safe:
  9. 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.

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

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

{ "message": "Hello from Next.js!" }

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.

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

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:

// 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` });
}

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

// 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 });
}

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.

// 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) });
}
// 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 });
}

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.

// 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}` });
}

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:

// 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}` });
}

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:

"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>
  );
}

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:

# .env.local
WEATHER_API_KEY=your-secret-key
// 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 });
}

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.

More from Next.js Tutorial