Skip to main content

What are API Routes in Next.js?

API Routes in Next.js are a way to create server-side API endpoints right inside a Next.js project, without a separate backend application. They let you handle requests, work with data, and return JSON just like a regular REST API.


Where they live

There are two options, depending on the router:

Pages Router

Files in the folder:

/pages/api/*.ts

Each file is a separate API endpoint.


App Router (Route Handlers)

Files of the form:

/app/api/.../route.ts

This is the modern version of API Routes, better integrated with the App Router.


Where the code runs

  • API Routes always run on the server
  • the code never reaches the browser
  • you can safely use:
    • secret keys
    • database access
    • server SDKs

Why they are needed

API Routes are used to:

  • hide API keys from the client
  • proxy requests to external APIs
  • work with a database
  • handle forms
  • do authorization
  • combine several data sources
  • implement simple backend logic

In effect, this is a mini-backend inside Next.js.


How they are used with the frontend

From the client they are called like a regular API:

js
fetch("/api/posts")

In this case:

  • the logic stays on the server
  • the client only gets the result

Difference from client-side fetching

  • client-side fetching - requests from the browser
  • API Routes - server-side code, which can be called:
    • from the client
    • from Server Components
    • from other API Routes

When API Routes are a good choice

  • small or medium server logic
  • no separate backend is needed
  • a fullstack application in a single repository
  • prototypes, startups, SaaS

When not to use them

  • complex business logic
  • heavy load
  • a microservices architecture
  • the need for long-running processes

In such cases, a separate backend is more common.


Short summary

  • API Routes are server endpoints inside Next.js
  • they run only on the server
  • suited for working with the DB, APIs, and secrets
  • let you do without a separate backend
  • in the App Router they are implemented through Route Handlers

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.