OpenAINext.jsFeb 28, 2025, 2:00 PM

Building APIs with Next.js

A condensed section focused on the key takeaways first.

Original Post

Quick Digest

Summary

A condensed section focused on the key takeaways first.

openaienmodel: gpt-5-mini-2025-08-07

Building APIs with Next.js — App Router & Route Handlers

Key Points

  • App Router uses web-standard Request/Response APIs
  • Export HTTP methods (GET/POST/etc.) in app/.../route.ts
  • Static SPA export disables dynamic server endpoints

Summary

This guide explains how to build HTTP APIs using Next.js App Router and Route Handlers. It covers project setup, placing route.ts files in app/, exporting method handlers (GET, POST, etc.), using the Web Request/Response APIs (NextRequest/NextResponse), handling query params, headers and cookies, dynamic route segments, reusable middleware wrappers, proxying/backends (BFF), and deployment trade-offs including static SPA export limits and Vercel deployment features.

Key Points

  • Initialize projects quickly: npx create-next-app@latest --api adds an example app/api/.../route.ts.
  • App Router (app/) uses Web standard Request/Response; prefer route.ts over pages/api/* for new apps.
  • Export per-method handlers in a single file (export async function GET/POST/PUT/DELETE) to handle multiple HTTP verbs.
  • Access request data via Request/NextRequest and return a Response/NextResponse; use request.nextUrl.searchParams for query params.
  • Read cookies and headers with next/headers helpers or via request.headers; NextRequest/NextResponse extend web APIs.
  • Create dynamic API routes with folder segments like app/api/users/[id]/route.ts and read params.id in handlers.
  • Build reusable middleware wrappers (e.g., withAuth) to centralize auth, logging, or validation across handlers.
  • Use Route Handlers as a proxy/BFF to call upstream services, forward auth, and transform responses.
  • Deployment: standard Node.js/next start supports full server features; SPA/output: 'export' static mode cannot run server endpoints (GET can be static only if not dynamic).
  • On Vercel you can deploy Route Handlers with platform features (firewall, cron jobs); consider a separate API service if you need full control or heavy compute.
  • Skip creating public API endpoints when server components can fetch private data directly for your Next.js app.

Actionable checklist for engineers

  • Add app/api/<route>/route.ts and export HTTP method functions.
  • Use NextRequest and cookies()/headers() for shared server logic.
  • Use dynamic segments for id-based routes and return proper status codes (200, 201, 204, 401).
  • Wrap common logic into small libs (e.g., lib/with-auth.ts) and reuse across handlers.
  • Evaluate deployment target: if you need server-side runtime features, avoid SPA/static-only export or host API separately.

Full Translation

Translations

A translation section that keeps the flow of the original article.

openaijamodel: gpt-5-mini-2025-08-07

Next.jsでAPIを構築する

概要

Next.jsでAPIを構築する方法を学びます。Next.jsはサーバーサイドで動作するAPIエンドポイントを簡単に作成でき、アプリケーションのフロントエンドと同一リポジトリでAPIを管理できます。

主な方法

  • Pages Router(pages/api
    • 従来の方法。pages/api/*.js にエンドポイントを作成すると、自動的にAPIルートになります。
  • App Router(Route Handlers)
    • app ディレクトリを使う場合、app/api/.../route.js のようにハンドラを定義します。HTTPメソッドごとに GET/POST 等の関数をエクスポートします。
  • Edge Runtime と Node.js Runtime
    • runtime = 'edge' を使うと低レイテンシのEdge環境で動作しますが、Nodeの組み込みモジュールが使えないなどの制約があります。

サンプル

  • Pages Router の例(pages/api/hello.js):

    export default function handler(req, res) { res.status(200).json({ message: 'Hello from Next.js API' }) }

  • App Router の例(app/api/hello/route.js):

    export function GET(request) { return new Response(JSON.stringify({ message: 'Hello from Next.js API' }), { status: 200, headers: { 'Content-Type': 'application/json' } }) }

注意点とベストプラクティス

  • 入力バリデーションとエラーハンドリングを行う。
  • 長時間実行する処理は背景ジョブやサーバーレス関数で切り離す。
  • Edge Runtime を使う場合、サポートされていないAPI(例: 一部のNode標準モジュール)に注意する。
  • 認証/認可はCookieやヘッダー、トークンを使って適切に実装する。

デプロイと運用

  • Vercel などのホスティングにそのままデプロイ可能。ローカルでの開発は npm run dev(または next dev)を使用。
  • ログ、モニタリング、レート制限を導入して運用性を高める。

まとめ

Next.jsを使えば、フロントエンドと同じフレームワーク内でAPIを素早く構築できます。用途に応じて pages/apiapp の Route Handlers を使い分け、ランタイムの制約を理解した上で設計してください。

Building APIs with Next.js | Next.js | DocsDigest