Encountering a TypeError while working with Next.js 14 and MongoDB: The error "res.status is not a function"

Currently working on a Next.js project that involves MongoDB integration. I am using the app router to test API calls with the code below, and surprisingly, I am receiving a response from the database.

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

// Handling 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`

Despite trying to log it to the console, I can't seem to resolve this error. The database is functioning properly, but I keep encountering a 500 server error.

I attempted a slightly different approach as shown 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() });
    });
}

Answer №1

It seems like you're blending the traditional approach (Pages Router) with the newer approach (App Router).

In versions 13 and 14 of Next.js, you can utilize both methods within the same project, but they should not be used interchangeably in the same location.

Your project may have APIs located in:

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

Here are examples of APIs found in each directory:

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 required and does not form part of the URL for calling)

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

    return Response.json({ allUsers })
}

For more information, visit: https://nextjs.org/docs/app/building-your-application/routing/route-handlers

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the CSS loader in webpack to malfunction?

I am currently working on implementing the toy example mentioned in the css-loader documentation which can be found at https://github.com/webpack-contrib/css-loader Additionally, I have also followed a basic guide that recommends similar steps: https://cs ...

Sluggish website loading time

Hey there, I'm currently developing a website and I'm facing a major issue with one of my pages loading slowly and experiencing lag. I'm unsure if this is due to the on scroll listeners or the excessive references in my code. Could it possib ...

Angular 4 yields an undefined result

I'm currently working on this piece of code and I need help figuring out how to return the value of rowData in this scenario. private createRowData() { const rowData: any[] = []; this.http .get(`/assets/json/payment.json`) .toPromise() .then(r ...

When attempting to utilize class validators in NestJS, Param is refusing to cast to DTO type

I'm currently working on implementing validation for the parameter I receive in a request, especially when trying to delete something. The parameter is expected to be a string but it must adhere to the format of a valid UUID. To achieve this, I have i ...

A helpful guide on fetching the Response object within a NestJS GraphQL resolver

Is there a way to pass @Res() into my graphql resolvers and make it work correctly? I tried the following, but it didn't work as expected: @Mutation(() => String) login(@Args('loginInput') loginInput: LoginInput, @Res() res: Response) ...

Is there a way to transform the searchParams function into an object? Changing from URLSearchParams { 'title' => '1' } to { title : 1 }

Is there a way to convert the searchParams function into an object, transforming from URLSearchParams { 'title' => '1' } to { title : 1 }? I need this conversion to be applied for all values in the URLSearchParams, not just one. Cur ...

Can Next.js 13 layout be cancelled in any way?

My website has three main pages: /, /accounts, and /signin I'm looking to implement a dashboard layout for the first two pages, while keeping a normal layout for the signin page. However, I'm stuck on how to achieve this. If I add the dashboard ...

Exploring Angular 2 with Visual Studio 2015 Update 1 in the context of Type Script Configuration

After spending the last week attempting to set up and launch a simple project, I am using the following configuration: Angular 2, Visual Studio 2015 update 1, TypeScript Configuration In the root of my project, I have a tsconfig.Json file with the follow ...

Is it possible to toggle between LTR and RTL styles with styled-components?

I am in the process of developing an app that supports both English and Arabic languages using next.js. I want to give users the ability to switch between the two languages. I came across this example on next.js: with-styled-components-rtl. It utilizes S ...

Identifying Movement of Mobile Device (NextJS)

Currently, I am utilizing Next 13 on my website and hoping to incorporate a feature that increments the counter every time a shake is detected on a mobile device. So far, I attempted using window.DeviceMotionEvent.requestPermission() to access the window.a ...

Resolving URL with Next.js context

Whenever I attempt to retrieve the URL on the server side using const { resolverUrl } = context, the URL includes characters '+' that are transformed into '%20' Is there a way to obtain the URL on the server side without this transfor ...

Exploring depths with Typescript recursion

I'm attempting to implement a recursive search in Typescript, but I am encountering an issue where TS is unable to determine the return type of the function. function findDirectory( directoryId: Key, directory: Directory, ) { if (!directory) ret ...

Issue with for loop execution within subscribe event

In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Da ...

Is there a way to access the rootPath or other client-side information from the language server side?

I'm currently developing a language extension based on the example "language server" available at https://code.visualstudio.com/docs/extensions/example-language-server. In order to determine the current folder being used by vscode on the server side, ...

Guide to defining a typescript class property using an index signature

type TField = { field1: string; field2: boolean; field3: TMyCustom; } class Test1 { // I opt for using TypeScript's index signature to declare class fields [key: keyof TField]: TField[typeof key] // Instead of individually declaring each ...

Toggle the visibility of a dropdown menu based on the checkbox being checked or unchecked

One challenge I am facing involves displaying and hiding DropDown/Select fields based on the state of a Checkbox. When the checkbox is checked, the Dropdown should be visible, and when unchecked, it should hide. Below is the code snippet for this component ...

Identifying Data Types in Typescript Using a Union Type Guard

I came across this interesting type guard: enum X { A = "1" } const isNullableX = (value: any): value is X | null => false let bar: string | null = '' if (isNullableX(bar)) { console.log(bar) } Surprisingly, in the last con ...

What is the best way to retrieve a specific field from the observable data stream?

When working with observables, I often find myself using them like this: ... const id = 1337; this.service.getThing(id).subscribe( suc => doSomething(suc.name), err = doSomethingElse() ); Lately, I've been utilizing the async pipe more freque ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Retrieve the document id along with the corresponding data from a collection

Retrieving data from the collection leads and displaying all documents in an HTML table. Upon clicking, I need to extract the document ID of the clicked item as it serves as the sole primary key. P.S I am able to obtain records of all documents in an arra ...