← Blog

Claude API Next.js App Router Integration Guide

2026-11-12 · 5 min read · SubToAPI Team

Integrating the Claude API into a Next.js App Router project means wiring up a server-side route handler that calls Anthropic's API (or a compatible gateway), then consuming that endpoint from client or server components. The App Router's conventions — route handlers in app/api/*/route.ts, server actions, and streaming responses via ReadableStream — map cleanly onto how LLM APIs work, but there are a few gotchas specific to Next.js: edge vs. node runtimes, environment variable scoping, and how you stream tokens back to the browser without blocking the render.

This guide walks through a working setup: a route handler that proxies requests to Claude, a streaming implementation that works with the App Router's response model, and a client component that renders tokens as they arrive. It also covers where things typically break — timeouts, runtime mismatches, and key exposure — so you don't have to debug them yourself.

Why the App Router Changes the Integration Pattern

If you're coming from the Pages Router or a plain Express backend, the main differences are:

Setting Up the Route Handler

Create a route handler that holds your API key server-side and forwards the request. Never call the Claude API directly from a client component — the key would end up in the browser bundle.

// app/api/chat/route.ts
export const runtime = "nodejs"; // or "edge" if your provider supports it

export async function POST(req: Request) {
  const { messages } = await req.json();

  const upstream = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`,
    },
    body: JSON.stringify({
      model: "claude-sonnet-4",
      max_tokens: 1024,
      stream: true,
      messages,
    }),
  });

  return new Response(upstream.body, {
    headers: { "Content-Type": "text/event-stream" },
  });
}

Store the key in .env.local as SUBTOAPI_KEY=sub_live_... and never prefix it with NEXT_PUBLIC_ — that prefix exposes it to the browser bundle, which defeats the point of a server-side proxy.

Streaming to the Client

The route handler above just passes the upstream stream through. On the client, use the Fetch API with a ReadableStream reader rather than EventSource, since EventSource only supports GET requests and you need POST to send the conversation payload.

"use client";
import { useState } from "react";

export function Chat() {
  const [output, setOutput] = useState("");

  async function send(prompt: string) {
    setOutput("");
    const res = await fetch("/api/chat", {
      method: "POST",
      body: JSON.stringify({ messages: [{ role: "user", content: prompt }] }),
    });

    const reader = res.body!.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      setOutput((prev) => prev + decoder.decode(value));
    }
  }

  return (
    <div>
      <button onClick={() => send("Explain the App Router in two sentences")}>
        Ask Claude
      </button>
      <p>{output}</p>
    </div>
  );
}

This renders tokens as they arrive instead of waiting for the full response, which matters a lot for perceived latency in chat UIs. For a deeper look at parsing SSE chunks correctly (including partial JSON frames), see /docs/streaming.

Using Server Actions Instead of a Route Handler

If you don't need streaming and just want a single request/response cycle — summarizing a form submission, classifying text, generating a short reply — a server action is simpler than a route handler:

// app/actions.ts
"use server";

export async function askClaude(prompt: string) {
  const res = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`,
    },
    body: JSON.stringify({
      model: "claude-sonnet-4",
      max_tokens: 512,
      messages: [{ role: "user", content: prompt }],
    }),
  });
  return res.json();
}

Call this directly from a form's action prop or from a client component via startTransition. No route handler, no manual fetch boilerplate — Next.js handles the serialization.

Why Go Through a Gateway Instead of Anthropic Directly

You can point the fetch calls above straight at Anthropic's API if you already have a direct API key. The reason to add a layer like SubToAPI in front is operational, not functional: it turns your existing Claude access into a standard HTTPS API with sub_live_... application keys, so you can issue a separate key per environment (dev, staging, production) or per team member without sharing your root credentials, and get usage metadata per key without building that tracking yourself. For a Next.js app with multiple contributors or multiple deployed environments, that separation avoids the common mistake of one shared key leaking into a client bundle or a public repo. Setup follows the same request shape shown above — check /docs/quickstart for the full flow and /docs/messages for the request/response schema.

Common Issues When Deploying

Questions

Can I call the Claude API directly from a Next.js client component? No — doing so exposes your API key in the browser bundle. Always proxy through a route handler or server action so the key stays server-side.

Should I use edge or nodejs runtime for streaming Claude responses? Either works for streaming, but nodejs is more forgiving with longer response times and fewer platform-specific limits. Use edge only if your host's edge runtime supports the duration you need.

Do I need a separate backend for Claude integration in Next.js? No. Route handlers and server actions in the App Router are sufficient — they run server-side within your Next.js deployment, so no separate backend service is required.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →