11

I am developing a tiny REST API for a Next.js app. If I place my route.ts in rootDir -> app -> api -> hello -> route.ts that looks like this, then it works:

//route.ts
export async function GET(request: Request) {
  return new Response('Hello, Next.js!')
}

I can make a successful GET request via Postman to localhost:3000/api/hello.

I change the code now to the following:

import { NextApiRequest, NextApiResponse } from "next";

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

Now it fails and I get the error message:

error TypeError: response.json is not a function

The issue is known but the upgrade to the latest lts or the latest node version does not fix my problem: https://github.com/vercel/next.js/issues/48524.

2 Answers 2

23

While your attempt would work in the pages directory of Next.js, the initial way of setting up routes, with the newer app folder you need to use the NextResponse object from next/server, as you can read on the doc:

import { NextResponse } from "next/server";

export async function GET(request: Request) {
  return NextResponse.json({ messsage: "Hello World" });
}
Sign up to request clarification or add additional context in comments.

Comments

2

It also will simply work with Response.json()

export function GET(request) {

  return Response.json({ messsage: 'Hello World' })
  // return new Response('Hello')
}

1 Comment

Why is this downvoted answer? This works for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.