R1SKY
R1SKY

Reputation: 115

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.

Upvotes: 9

Views: 26035

Answers (5)

mrconcerned
mrconcerned

Reputation: 1965

After checking documentation I can tell that calls just take request parameter like:

export async function GET(request: Request) {
}

but you can also replace Request with NextRequest.

In my case, I'm using Request, to get the authentication token from the header and get the specific user with JWT.

export async function GET(req: Request) {
    if (req.method !== 'GET') {
        return Response.json({ message: "Method Not Allowed" }, { status: 405 });
    }
    try {
        // Verify the access token
        const decoded = verifyToken(req) as JwtPayload;
        const userId = decoded.uid;

        // Fetch the user details from the database
        const user = await prisma.user.findUnique({
            where: { id: userId },
            select: { id: true, email: true, name: true }
        });

        if (!user) {
            return Response.json({ message: "User not found" }, { status: 404 });
        }
        return Response.json({ user }, { status: 200 });
    } catch (error) {
        console.error('Error fetching user:', error);
        return Response.json({ message: "Internal Server Error" }, { status: 500 });
    } finally {
        await prisma.$disconnect();
    }
}

I hope it helps someone.

Upvotes: 0

Alioth
Alioth

Reputation: 9

Change the folder

src/app/api/timetable -> src/pages/api/timetable

Upvotes: -3

Suraj Pandey
Suraj Pandey

Reputation: 11

I use this one is js and it works.

export function GET (req,res){
    Response.json({Msg:"your message"}, {status:200});
}

Upvotes: 1

Funsho
Funsho

Reputation: 81

This does not work becasue Next 14 does not use import { NextApiRequest, NextApiResponse } from "next";

You can redo it like this

//app/api/test/route.js

import { NextResponse } from 'next/server'
 
export async function GET(request: Request) {
  return NextResponse.json({ msg: 'Hello from server' })
}

Im sure with this you get the gist and can take it from here.

Here is a full reference with explanation from their website

https://nextjs.org/docs/app/building-your-application/routing/route-handlers

https://nextjs.org/docs/app/api-reference/functions/next-response#json

Hope this helps

Upvotes: 8

grekier
grekier

Reputation: 3726

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.

Upvotes: 6

Related Questions