Search code examples
typescriptnext.js

Nextjs 14 and mongoDB TypeError: res.status is not a function on GET request


working on a nextjs project using mongodb. Using app router, trying to test api calls using the following code, weirdly enough I get a response from the db

import { NextApiRequest, NextApiResponse, NextApiHandler } from "next";
import User from "../../model/User";
import clientPromise from "../../lib/mongodb";

// Handle GET method
export const GET: NextApiHandler = async (req, res) => {
  await clientPromise;
  const allUsers = await User.find({})
    .then((data) => {
      console.log(data);
      return res.status(200).json(data);
    })
    .catch((err) => {
      console.log(err);
      return res.status(500).json({ error: err.toString() });
    });
};

TypeError: res.status is not a function`

I have tried to console log it but the error is never cleared. DB is happy but just keep getting 500 server error

I have tried doing this slightly different as below

export async function GET(req: NextApiRequest, res: NextApiResponse) {
  await clientPromise;
  const allUsers = await User.find({})
    .then((data) => {
      console.log(data);
      return res.status(200).json(data);
    })
    .catch((err) => {
      console.log(err);
      return res.status(500).json({ error: err.toString() });
    });
}

Solution

  • I think you're mixing the old way (Pages Router) and the new way (App Router).

    It's possible to use both forms in the same Next.js project versions 13 and 14, but not in the same place.

    In your project, you can have APIs in:

    1. Page Router: /pages/api/ or src/pages/api/
    2. App Router: /app/api or src/app/api/

    Here are two examples of APIs in both directories:

    File: /src/pages/api/users/index.ts or /src/pages/api/users.ts

    import type { NextApiRequest, NextApiResponse } from 'next'
    
    export default function handler(req: NextApiRequest, res: NextApiResponse) {
        const allUsers = {
            users: [
                {
                    id: 1,
                    name: 'John Doe',
                },
                {
                    id: 2,
                    name: 'foo bar',
                },
            ],
        }
    
        return res.status(200).json({ allUsers })
    }
    

    File: /src/app/api/users/route.ts (the name route is mandatory and is not part of the URL to call)

    export async function GET() {
        const allUsers = {
            users: [
                {
                    id: 1,
                    name: 'john Doe',
                },
                {
                    id: 2,
                    name: 'Foo Bar',
                },
            ],
        }
    
        return Response.json({ allUsers })
    }
    

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