KoderSolutionKoderSolution LogoKoderSolution Logo
HomeArticlesTutorialsToolsRun CodeForumAI Lab
▲

Next.js

Topic Hub & Articles

Next.js Intro

10 min

Next.js Installation

10 min

Next.js Routing

10 min

Next.js Pages

10 min

Next.js App Router

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Layouts

10 min

Next.js Linking and Navigating

10 min

Next.js Loading UI and Streaming

10 min

Next.js Error Handling

10 min

Next.js Data Fetching

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Server Actions

10 min

Next.js Rendering

10 min

Next.js CSS Modules

10 min

Next.js Image Optimization

10 min

Next.js Font Optimization

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Script Optimization

10 min

Next.js Static File Serving

10 min

Next.js Metadata

10 min

Next.js API Routes

10 min

Next.js Middleware

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Authentication

10 min

Next.js Deployment

10 min

Next.js Internationalization

10 min

Next.js Security

10 min

Next.js Performance

10 min

Recap Quiz

Gated

Milestone Assessment

Progress
0%

0 / 25 Lessons

KoderSolutionKoderSolution LogoKoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Facebook PageX (Twitter) ProfileYouTube ChannelContact Support

Engineering Newsletter

Subscribe for weekly software engineering tutorials, architecture guides, and developer tool updates.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
Next.jsNext.js Tutorial
Lesson

Next.js API Routes

10 min reading
Free Course

Next.js API Routes: Building Route Handlers in app/

Next.js API routes in the App Router are called Route Handlers and live inside route.ts files. They let you create custom HTTP endpoints for webhooks, mobile clients, OAuth callbacks, and third-party API integrations using standard Web Request and Response objects.

Export async functions named after HTTP methods (GET, POST, PUT, PATCH, DELETE) from any folder under app/api/.

flowchart LR
    A["HTTP Request"] --> B["app/api/items/route.ts"]
    B --> C{"HTTP Method"}
    C -- "GET" --> D["Run GET() Handler"]
    C -- "POST" --> E["Run POST() Handler"]
    D & E --> F["Return NextResponse.json()"]

Writing GET and POST Route Handlers

Return structured JSON and explicit HTTP status codes using NextResponse.json().

// app/api/items/route.ts
import { NextRequest, NextResponse } from 'next/server';

interface Item {
  id: number;
  name: string;
}

const items: Item[] = [
  { id: 1, name: 'Mechanical Keyboard' },
  { id: 2, name: 'USB-C Hub' },
];

export async function GET() {
  return NextResponse.json({ items }, { status: 200 });
}

export async function POST(request: NextRequest) {
  const body = await request.json();
  if (!body?.name || typeof body.name !== 'string') {
    return NextResponse.json({ error: 'Item name is required' }, { status: 400 });
  }

  const created: Item = { id: Date.now(), name: body.name.trim() };
  items.push(created);
  return NextResponse.json({ item: created }, { status: 201 });
}

Reading Query Params and Dynamic Segments

Read search parameters via request.nextUrl.searchParams and dynamic URL segments via the second context argument.

// app/api/items/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const currency = request.nextUrl.searchParams.get('currency') ?? 'USD';

  return NextResponse.json({
    id,
    currency,
  });
}

When to Choose Route Handlers vs. Server Actions

Use Server Actions for form submissions and UI mutations inside your Next.js frontend. Use route.ts Route Handlers when external services, Stripe webhooks, or mobile apps need an HTTP endpoint.

Common Mistakes

  • Placing page.tsx and route.ts in the same folder: A single URL path cannot serve both a React page and a Route Handler; keep API files under app/api/.
  • Calling fetch('/api/items') from a Server Component: Server Components already run on the server, so import your data helper directly instead of making an extra HTTP loop.
  • Forgetting to parse or validate request.json(): Unvalidated payloads can crash handlers when clients send malformed JSON or missing fields.

Frequently Asked Questions

Are GET Route Handlers cached by default in Next.js 15+?

No, starting in Next.js 15, GET handlers are uncached by default unless you export export const dynamic = 'force-static';.

How do I handle dynamic webhook signatures in route.ts?

Read the raw body with await request.text() before verifying HMAC headers from providers like Stripe or GitHub.

Can I set HTTP-only cookies inside a Route Handler?

Yes, create a response with NextResponse.json(...) and call response.cookies.set('session', token, { httpOnly: true, path: '/' }).

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Related Developer Tools & Topic Hub

Next.js Topic Hub
JSON Formatter
Validate and format JSON payloads
HTML Formatter
Format HTML markup
CSS Formatter
Clean and format stylesheets
All Next.js Articles
Deep-dive guides, tips & discussions
PreviousNext.js Metadata
Continue JourneyNext: Next.js Middleware

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum