Frameworks Knowledge Base

Working with JSON in Next.js: Server & Client Patterns

Complete Next.js JSON guide: building JSON API routes, fetching in getServerSideProps and getStaticProps, Server Components, and SWR on the client.

In Next.js, create JSON API routes by exporting a handler function from app/api/ that calls res.json(). Fetch data server-side in Server Components with async fetch() or client-side with SWR.

JSON Patterns in Next.js (App Router)

Next.js provides multiple JSON data fetching strategies depending on rendering requirements: Server Components (RSC), API Route Handlers, and Client Components.

API Route Handlers (App Router)

Create files in app/api/*/route.ts that export named HTTP method functions returning Response.json().

json
// app/api/users/route.ts — JSON API Route Handler
import { NextResponse } from 'next/server';

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

export async function POST(request: Request) {
  const body = await request.json(); // Parse JSON body
  const created = await db.users.create({ data: body });
  return NextResponse.json(created, { status: 201 });
}

// app/users/page.tsx — Server Component fetch
async function UsersPage() {
  const res = await fetch('/api/users', { cache: 'no-store' });
  const users = await res.json();
  return <ul>{users.map((u: User) => <li key={u.id}>{u.name}</li>)}</ul>;
}

// Client Component with SWR
'use client';
import useSWR from 'swr';

const fetcher = (url: string) => fetch(url).then(r => r.json());

function ClientUsers() {
  const { data, error } = useSWR('/api/users', fetcher);
  if (error) return <p>Error loading users</p>;
  if (!data) return <p>Loading...</p>;
  return <ul>{data.map((u: User) => <li key={u.id}>{u.name}</li>)}</ul>;
}

Try the free JSON to TypeScript

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON to TypeScript

Frequently Asked Questions

How do I create a JSON API route in Next.js App Router?

Export a named GET or POST function from app/api/[route]/route.ts and return NextResponse.json(data).

How do I fetch JSON in a Next.js Server Component?

Use the native fetch() API directly in your async Server Component function with await.

How do I parse a JSON request body in a Next.js route handler?

Call await request.json() inside your route handler function to parse the incoming JSON body.

Related JSON Topics & Reference Articles