API routes are used to create Backend endpoints in Next.js without needing a separate server in Express or Node.js.
API Routes are server-side functions stored in the /app/api (App Router) or /pages/api (Pages Router) directory.
Note:
- Next.js is used as a full-stack framework.
- API Routes are server-side functions.
Why API Routes are Important?
There are many points to show that API routes are very important.
1. There is no need for a separate backend.
2. It is secure, because it’s a server-side only.
3. Supports SSR + API in one project.
4. Works with Next.js features (Middleware, Edge Functions, Route Handlers).
Where to Write API Routes?
We have two routers, so I will tell you about each one.
1. App Router
Suppose you have to create a quiz route, so you will create a quiz folder and then create a route.js file.
Example:
app/api/quiz/route.js
Example: In route.js
export function GET() {
return Response.json({ message: "Hello TechFliez!" });
}
2. Pages Router
Suppose you have to create a quiz route, so you will create a quiz.js file.
Example:
pages/api/quiz.js
What Are API Routes in Next.js? – Interview Questions
Q 1: What are API routes?
Ans: Backend endpoints created within a Next.js application.
Q 2: Where are API routes located?
Ans: Inside the app/api/ directory.
Q 3: What HTTP methods are supported?
Ans: GET, POST, PUT, PATCH, DELETE.
Q 4: Are API routes server-only?
Ans: Yes, they run only on the server.
Q 5: Can API routes access databases?
Ans: Yes, securely.
What Are API Routes in Next.js? – Objective Questions (MCQs)
Q1. API Routes in Next.js are used to:
Q2. In the App Router, API routes are created inside:
Q3. Which file name is required for an API route in App Router?
Q4. API Routes in Next.js run on:
Q5. API Routes can be used to: