How to build REST and GraphQL APIs using Next.js Route Handlers. Covers NextRequest, NextResponse, cookies(), headers(), and real examples from my GraphQL API and webhook endpoints.
Below is a concise, self-contained summary and reference based on your examples, suitable for a portfolio or documentation section.
Route Handlers are the App Router way to build API endpoints in Next.js. Instead of using pages/api, you colocate API logic inside the app directory:
File-based routing: app/api/<route>/route.ts
Export functions named after HTTP methods (GET, POST, etc.)
Use NextRequest and NextResponse for extended Web API features
They’re ideal for:
Custom REST or GraphQL APIs
Webhooks (e.g., CMS, payment providers)
Server-side utilities that don’t fit Server Actions
This route exposes a GraphQL endpoint with environment-aware configuration, CORS, and GraphiQL in development.
```ts
// app/api/graphql/route.ts
import { createYoga } from 'graphql-yoga';
import { schema } from '@/graphql/schema';
import { NextRequest } from 'next/server';
const { handleRequest } = createYoga({
schema,
graphqlEndpoint: '/api/graphql',
// Enable GraphiQL only in development
graphiql: process.env.NODE_ENV === 'development',
// CORS configuration
cors: {
origin:
process.env.NODE_ENV === 'production'
? process.env.NEXTPUBLICSITE_URL || '*'