How to read JSON with Next.js 13 API routes
Use the request methods instead of the body property to read JSON.
tldr;
const data = await request.json()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:
Request.arrayBuffer()- Returns a promise that resolves with anArrayBufferrepresentation of the request body.Request.blob()- Returns a promise that resolves with aBlobrepresentation of the request body.Request.formData()- Returns a promise that resolves with aFormDatarepresentation of the request body.Request.json()- Returns a promise that resolves with the result of parsing the request body asJSON.Request.text()- Returns a promise that resolves with a text representation of the request body.
Each of these methods returns a Promise, so ensure you await the result before you use it.