1 min read

How to read JSON with Next.js 13 API routes

Use the request methods instead of the body property to read JSON.
How to read JSON with Next.js 13 API routes
Photo by Ferenc Almasi / Unsplash

tldr;

const data = await request.json()
How to read JSON from Next.js 13 API Routes

The Request Object

Next.js 13 has support for API routes in the app directory. These routes have a new function signature:

export async function GET(request: Request) {
  // do things here
  return Response.json({ hello: 'world' })
}

The Request object is a standard web request (docs). The body property is a read-only ReadableStream, which you could use, but it's not elegant. Instead, you want to use the helper methods the Request object provides to parse the data:

Each of these methods returns a Promise, so ensure you await the result before you use it.