How to send a JSON response from an API route in Next.js? – Next.js

by
Ali Hasan
django-rest-framework next.js node.js

Quick Fix: To send a JSON response from an API route in Next.js using the app folder, import the NextResponse object from next/server and use NextResponse.json({ messsage: "Hello World" }) to return a JSON response.

The Problem:

I am trying to send a JSON response from an API route in Next.js. I have tried using the response.json() method, but I’m getting a TypeError: response.json is not a function error. I have checked that I am using the latest version of Next.js and Node.js, but the issue persists.

The Solutions:

Solution 1: Using `NextResponse` object

In the Next.js app directory, the response.json method is not available for API routes. Instead, you need to use the NextResponse object from the next/server library.

import { NextResponse } from "next/server";

export async function GET(request: Request, response: NextApiResponse) {
  return NextResponse.json({ message: "Hello, Next.js!" });
}

Q&A

The API route is fine. But the server side code is not correct. What’s the change I need to do?

Use NextResponse from next/server to return a JSON response from an API route.

Where to import NextResponse ?

Import NextResponse from next/server in the API route file.

Video Explanation:

The following video, titled "How to Build a REST API with Next.js 13 - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... nextjs How to Build a REST API with Next.js 13 (00:00) Intro (00:05) Welcome (00:25) Next.js New Route Handlers (00:43) When to use API Routes ...