route-handlers

This skill should be used when the user asks to "create an API route", "add an endpoint", "build a REST API", "handle POST requests", "create route handlers", "stream responses", or needs guidance on Next.js API development in the App Router.

2,707 stars

Best use case

route-handlers is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

This skill should be used when the user asks to "create an API route", "add an endpoint", "build a REST API", "handle POST requests", "create route handlers", "stream responses", or needs guidance on Next.js API development in the App Router.

Teams using route-handlers should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/route-handlers/SKILL.md --create-dirs "https://raw.githubusercontent.com/davepoon/buildwithclaude/main/plugins/nextjs-expert/skills/route-handlers/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/route-handlers/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How route-handlers Compares

Feature / Agentroute-handlersStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

This skill should be used when the user asks to "create an API route", "add an endpoint", "build a REST API", "handle POST requests", "create route handlers", "stream responses", or needs guidance on Next.js API development in the App Router.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Next.js Route Handlers

## Overview

Route Handlers allow you to create API endpoints using the Web Request and Response APIs. They're defined in `route.ts` files within the `app` directory.

## Basic Structure

### File Convention

Route handlers use `route.ts` (or `route.js`):

```
app/
├── api/
│   ├── users/
│   │   └── route.ts      # /api/users
│   └── posts/
│       ├── route.ts      # /api/posts
│       └── [id]/
│           └── route.ts  # /api/posts/:id
```

### HTTP Methods

Export functions named after HTTP methods:

```tsx
// app/api/users/route.ts
import { NextResponse } from 'next/server'

export async function GET() {
  const users = await db.user.findMany()
  return NextResponse.json(users)
}

export async function POST(request: Request) {
  const body = await request.json()
  const user = await db.user.create({ data: body })
  return NextResponse.json(user, { status: 201 })
}
```

Supported methods: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`

## Request Handling

### Reading Request Body

```tsx
export async function POST(request: Request) {
  // JSON body
  const json = await request.json()

  // Form data
  const formData = await request.formData()
  const name = formData.get('name')

  // Text body
  const text = await request.text()

  return NextResponse.json({ received: true })
}
```

### URL Parameters

Dynamic route parameters:

```tsx
// app/api/posts/[id]/route.ts
interface RouteContext {
  params: Promise<{ id: string }>
}

export async function GET(
  request: Request,
  context: RouteContext
) {
  const { id } = await context.params
  const post = await db.post.findUnique({ where: { id } })

  if (!post) {
    return NextResponse.json(
      { error: 'Not found' },
      { status: 404 }
    )
  }

  return NextResponse.json(post)
}
```

### Query Parameters

```tsx
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const page = searchParams.get('page') ?? '1'
  const limit = searchParams.get('limit') ?? '10'

  const posts = await db.post.findMany({
    skip: (parseInt(page) - 1) * parseInt(limit),
    take: parseInt(limit),
  })

  return NextResponse.json(posts)
}
```

### Request Headers

```tsx
export async function GET(request: Request) {
  const authHeader = request.headers.get('authorization')

  if (!authHeader?.startsWith('Bearer ')) {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { status: 401 }
    )
  }

  const token = authHeader.split(' ')[1]
  // Validate token...

  return NextResponse.json({ authenticated: true })
}
```

## Response Handling

### JSON Response

```tsx
import { NextResponse } from 'next/server'

export async function GET() {
  return NextResponse.json(
    { message: 'Hello' },
    { status: 200 }
  )
}
```

### Setting Headers

```tsx
export async function GET() {
  return NextResponse.json(
    { data: 'value' },
    {
      headers: {
        'Cache-Control': 'max-age=3600',
        'X-Custom-Header': 'custom-value',
      },
    }
  )
}
```

### Setting Cookies

```tsx
import { cookies } from 'next/headers'

export async function POST(request: Request) {
  const cookieStore = await cookies()

  // Set cookie
  cookieStore.set('session', 'abc123', {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    maxAge: 60 * 60 * 24 * 7, // 1 week
  })

  return NextResponse.json({ success: true })
}
```

### Redirects

```tsx
import { redirect } from 'next/navigation'
import { NextResponse } from 'next/server'

export async function GET() {
  // Option 1: redirect function (throws)
  redirect('/login')

  // Option 2: NextResponse.redirect
  return NextResponse.redirect(new URL('/login', request.url))
}
```

## Streaming Responses

### Text Streaming

```tsx
export async function GET() {
  const encoder = new TextEncoder()
  const stream = new ReadableStream({
    async start(controller) {
      for (let i = 0; i < 10; i++) {
        controller.enqueue(encoder.encode(`data: ${i}\n\n`))
        await new Promise(resolve => setTimeout(resolve, 100))
      }
      controller.close()
    },
  })

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
    },
  })
}
```

### AI/LLM Streaming

```tsx
export async function POST(request: Request) {
  const { prompt } = await request.json()

  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }],
    stream: true,
  })

  const stream = new ReadableStream({
    async start(controller) {
      for await (const chunk of response) {
        const text = chunk.choices[0]?.delta?.content || ''
        controller.enqueue(new TextEncoder().encode(text))
      }
      controller.close()
    },
  })

  return new Response(stream, {
    headers: { 'Content-Type': 'text/plain' },
  })
}
```

## CORS Configuration

```tsx
export async function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  })
}

export async function GET() {
  return NextResponse.json(
    { data: 'value' },
    {
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
    }
  )
}
```

## Caching

### Static (Default for GET)

```tsx
// Cached by default
export async function GET() {
  const data = await fetch('https://api.example.com/data')
  return NextResponse.json(await data.json())
}
```

### Opt-out of Caching

```tsx
export const dynamic = 'force-dynamic'

export async function GET() {
  // Always fresh
}

// Or use cookies/headers (auto opts out)
import { cookies } from 'next/headers'

export async function GET() {
  const cookieStore = await cookies()
  // Now dynamic
}
```

## Error Handling

```tsx
export async function GET(request: Request) {
  try {
    const data = await riskyOperation()
    return NextResponse.json(data)
  } catch (error) {
    console.error('API Error:', error)

    if (error instanceof ValidationError) {
      return NextResponse.json(
        { error: error.message },
        { status: 400 }
      )
    }

    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    )
  }
}
```

## Resources

For detailed patterns, see:
- `references/http-methods.md` - Complete HTTP method guide
- `references/streaming-responses.md` - Advanced streaming patterns
- `examples/crud-api.md` - Full CRUD API example

Related Skills

app-router

2707
from davepoon/buildwithclaude

This skill should be used when the user asks to "create a Next.js route", "add a page", "set up layouts", "implement loading states", "add error boundaries", "organize routes", "create dynamic routes", or needs guidance on Next.js App Router file conventions and routing patterns.

soft-screening-startup

2707
from davepoon/buildwithclaude

Activate for ANY startup evaluation, investment screening, or company assessment. Triggers include: "evaluate this startup", "screen this company", "should I invest in X", "is this a good investment", "what do you think about this company", "review this startup", "score this company", "rate this pitch", "assess this founder", "quick take on X", "is X worth investing in", "pass or decline on X", "what's your verdict on X", "first look at this company", "quick screen on X", "what's your take on this founder", "is this fundable", "would a VC invest in this". Also triggers when a user pastes a company description, funding ask, or founder background and asks for an opinion. Works on claude.ai and Claude Code. For hard-mode deterministic scoring with Python audit trail, use /venture-capital-intelligence:hard-screening-startup.

market-size

2707
from davepoon/buildwithclaude

Run TAM/SAM/SOM market sizing with top-down and bottom-up methods, competitive landscape, and tech stack analysis. Triggered by: "/venture-capital-intelligence:market-size", "size this market", "what is the TAM for X", "market sizing analysis", "competitive landscape for X", "who are the competitors", "TAM SAM SOM for X", "market opportunity analysis", "how big is this market", "is this market big enough", "what's the addressable market", "total addressable market for X", "how large is the opportunity", "market research for X", "how saturated is this market", "market size estimate", "go-to-market sizing", "what is the serviceable market". Claude Code only. Requires Python 3.x. Uses web search for market data.

hard-screening-startup

2707
from davepoon/buildwithclaude

Deterministic Python-scored startup screening with full audit trail. Use when you need a reproducible, weighted-score verdict on a startup — not just a qualitative opinion. Triggered by: "/venture-capital-intelligence:hard-screening-startup", "hard screen this startup", "run a hard screen on X", "score this startup with Python", "give me an auditable screen", "run a scored evaluation on X", "give me a weighted score for this startup", "screen with numbers", "objective startup score", "reproducible screen", "investment scorecard for X", "score this company out of 100", "run the full screen on X". Claude Code only. Requires Python 3.x. For conversational soft-mode screening, use /venture-capital-intelligence:soft-screening-startup.

fund-operations

2707
from davepoon/buildwithclaude

Compute fund KPIs (TVPI, DPI, IRR, MOIC), model carried interest and management fees, and generate LP quarterly update narratives. Triggered by: "/venture-capital-intelligence:fund-operations", "calculate fund KPIs", "what is my fund TVPI", "IRR calculation", "compute MOIC", "LP report", "quarterly update draft", "carried interest calculation", "management fee calculation", "fund performance report", "write my LP update", "how is my fund performing", "what is my DPI", "fund returns analysis", "model my carry", "how much carry do I earn", "portfolio performance summary", "generate investor update". Claude Code only. Requires Python 3.x.

financial-model

2707
from davepoon/buildwithclaude

Run deterministic financial models for startup valuation and SaaS health analysis. Triggered by: "/venture-capital-intelligence:financial-model", "run a financial model on X", "DCF this company", "model the financials", "calculate runway", "what is the valuation", "SaaS metrics model", "LTV CAC analysis", "unit economics", "burn rate analysis", "comparable valuation", "how long is my runway", "what's my burn multiple", "revenue projection for X", "model the ARR growth", "what is the pre-money valuation", "comps analysis", "NRR and churn model", "how healthy are these SaaS metrics". Claude Code only. Requires Python 3.x. Accepts user-supplied numbers or searches for publicly available data.

explain-equity-terms

2707
from davepoon/buildwithclaude

Activate for ANY equity, legal, or term sheet question related to startup investing or fundraising. Triggers include: "what is a SAFE", "explain this term sheet", "what does pro-rata mean", "what is liquidation preference", "explain anti-dilution", "ISO vs NSO", "what is a 83(b) election", "what is carried interest", "explain drag-along", "what is a valuation cap", "what does MFN mean", "explain convertible note vs SAFE", "what is a down round", "explain vesting cliff", "what does fully diluted mean", "term sheet question", "equity question", "what does this clause mean". Also triggers when a user pastes legal text from a term sheet, SAFE, or subscription agreement and asks what it means. Works on claude.ai and Claude Code.

deal-sourcing-signals

2707
from davepoon/buildwithclaude

Scan a company or sector for deal-sourcing signals across 6 dimensions. Triggered by: "/venture-capital-intelligence:deal-sourcing-signals", "scan signals for X", "what signals is X showing", "deal sourcing scan", "hiring signals for X", "is X raising soon", "monitor this company", "company signal scan", "sourcing brief for X", "what is X up to", "is X growing", "track this company", "deal signal report for X", "is this company fundraising", "what are the momentum signals for X", "find signals on X", "is X worth tracking". Claude Code only. Requires Python 3.x. Uses web search for live signal data.

cap-table-waterfall

2707
from davepoon/buildwithclaude

Model cap table dilution, SAFE conversion, and exit waterfall across scenarios. Triggered by: "/venture-capital-intelligence:cap-table-waterfall", "model my cap table", "simulate dilution", "SAFE conversion math", "exit waterfall", "how much do I own after Series A", "liquidation waterfall", "cap table scenario", "what happens to equity at exit", "model the waterfall", "how much equity do I have left", "what is my ownership after funding", "run dilution scenarios", "model a new round", "what happens at acquisition", "cap table after SAFE conversion", "pari passu waterfall", "preference stack analysis". Claude Code only. Requires Python 3.x.

analyze-pitch-deck

2707
from davepoon/buildwithclaude

Activate for ANY pitch deck analysis, feedback, or review request. Triggers include: "analyze this deck", "review my pitch deck", "critique my pitch", "feedback on my slides", "is my deck investor ready", "what's wrong with my pitch", "how would a VC react to this deck", "score my pitch deck", "rate my slides", "improve my deck", "what slides am I missing", "is this pitch compelling". Also triggers when a user pastes slide content, describes their deck structure, or shares a company narrative and asks for investor feedback. Works on claude.ai and Claude Code.

public-plugin-builder

2707
from davepoon/buildwithclaude

Activate when the user wants to build a Claude plugin, create a Claude skill, make a Claude agent, structure a Claude Code plugin, says "build a plugin", "create a skill", "new claude skill", "new agent", "help me make a plugin", "plugin builder", "claude plugin helper", "how do I build a Claude skill", "I want to create a Claude plugin", "plugin building", or asks how to structure a Claude Code plugin or publish to the Claude marketplace. Works on both claude.ai (generates files as code blocks) and Claude Code (writes and pushes files).

server-components

2707
from davepoon/buildwithclaude

This skill should be used when the user asks about "Server Components", "Client Components", "'use client' directive", "when to use server vs client", "RSC patterns", "component composition", "data fetching in components", or needs guidance on React Server Components architecture in Next.js.