API Routes in Next.js

📘 Next.js 👁 32 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

API Routes in Next.js allow you to build backend APIs directly inside your Next.js application. You can handle requests, connect to databases, and perform server-side logic without setting up a separate backend server.


1. What are API Routes?

API Routes are server-side functions that respond to HTTP requests such as GET, POST, PUT, DELETE.
They run only on the server and are not included in the client-side bundle.


2. API Routes in App Router (Recommended)

In the App Router, API routes are created using route.js inside the app/api directory.

Folder Structure

app/ └── api/ └── posts/ └── route.js

3. Basic API Route Example

GET Request

export async function GET() { return new Response( JSON.stringify({ message: 'Hello from API' }), { status: 200 } ); }

Access URL:

/api/posts

4. Handling Different HTTP Methods

export async function GET() { return Response.json({ posts: [] }); } export async function POST(request) { const body = await request.json(); return Response.json({ success: true, body }); }

Supported methods:

  • GET

  • POST

  • PUT

  • PATCH

  • DELETE


5. Request Parameters

Query Parameters

/api/posts?id=1
export async function GET(request) { const { searchParams } = new URL(request.url); const id = searchParams.get('id'); return Response.json({ id }); }

Dynamic API Routes

app/ └── api/ └── posts/ └── [id]/ └── route.js
export async function GET(request, { params }) { return Response.json({ postId: params.id }); }

6. Connecting to a Database (Example)

import { connectDB } from '@/lib/db'; export async function GET() { const posts = await connectDB().find(); return Response.json(posts); }

7. API Routes in Pages Router (Older)

pages/ └── api/ └── users.js
export default function handler(req, res) { res.status(200).json({ message: 'Hello API' }); }

8. Security and Best Practices

  • Use environment variables (.env.local)

  • Validate request data

  • Handle errors properly

  • Do not expose sensitive logic to the client


Use Cases

  • Authentication

  • CRUD operations

  • Form handling

  • Database interactions

  • Third-party API integration


Conclusion

API Routes make Next.js a full-stack framework, allowing you to build both frontend and backend in a single project. Using the App Router, you can create clean, scalable, and secure APIs with minimal setup.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes