restnext.js

How do i define an api route in next js 14?


I'm trying to build a simple REST api. I have a route.ts file inside of src/app/api/timetable folder. Here is my route.ts:

import { NextApiRequest, NextApiResponse } from "next";

type ResponseData = {
  message: string
}
 
export function GET(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.status(200).json({ message: 'Hello from Next.js!' })
}

So its just basic example from docs. When I call this endpoint at localhost:3000/api/timetable I'm getting TypeError: res.status is not a function.

I'm using app router, typescript has the version 5.1.3, next js is 14.0.3

I tried to place it inside pages folder (like page router), it didn't help.


Solution

  • Change the definition to

    export function GET(
      req: NextApiRequest,
    ) {
      return Response.json({ message: 'Hello from Next.js!' })
    }
    

    There is no Response in the method definition.