skip to Main Content

I have a dynamic API route file for the POST request. Here is the code of that file:

import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/dbConnect";
import User from "@/models/User";

export async function POST(req: NextRequest, res: NextResponse) {
    const data = await req.json();
    const { name, email, password, country } = data;
    await dbConnect();

    try {
        const user = await User.create({
            name, email, password, country
        })
        return NextResponse.json({
            success: true,
            data: user,
        }, {
            status: 201,
        })
    } catch (error) {
        return NextResponse.json({
            success: false,
        }, {
            status: 400,
        })
    }
}

If I try to replace NextResponse inside the route with res, it gives me an error. Here’s what I mean:

return res.json({
            success: true,
            data: user,
        }, {
            status: 201,
        })

Here’s the error that it’s giving me: Expected 0 arguments, but got 2.ts(2554) .

Error screenshot

Why I can’t replace NextResponse with res?

2

Answers


  1. If you need to use res for your use-case, you can use:

    export async function POST(req: NextRequest, res: NextApiResponse) {
        ...
    
        try {
            return res.status(201).json({
                success: true,
                data: user,
            })
        } catch (error) {
            return res.status(400).json({ success: false })
        }
    }
    

    Do note that res must be of type NextApiResponse and not NextResponse.

    Login or Signup to reply.
  2. Since you have that export async function POST, you are most likely using the new app router (directory), and there, an API route gets passed as parameter only the request.

    To send a response back, you have to return a Response or use NextResponse from next/server, for example:

    import { NextResponse } from "next/server";
    
    export async function GET(request: Request) {
      const { searchParams } = new URL(request.url);
      const id = searchParams.get("id");
    
      const res = await fetch(`https://data.mongodb-api.com/product/${id}`);
      const product = await res.json();
    
      return NextResponse.json({ product });
    }
    

    The res of type NextApiResponse goes with req of type NextApiRequest, but they are for API routes in the initial pages router (directory).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search