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

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

Creating dynamic SQL queries for bulk inserting data into Postgres using Vercel

Can anyone help me with creating an SQL bulk insert query using the sql helper from @vercel/postgres? I have a array of objects with different property types (number, string, date) and need to dynamically build the query. Simply creating a string and passi ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

What is the best way to provide transformers in ts-node?

Currently, I am in the process of creating my own compiler for Typescript because I require the usage of transformers. Within our workflow, we utilize ts-node to execute specific files (such as individual tests), and it is essential that these transformer ...

Is there a function return type that corresponds to the parameter types when the spread operator is used?

Is it possible to specify a return type for the Mixin() function below that would result in an intersection type based on the parameter types? function Mixin(...classRefs: any[]) { return merge(class {}, ...classRefs); } function merge(derived: any, ... ...

I keep receiving data despite PHP showing a connection refused error

Something strange is happening here. I have a php server running on a remote location and a next.js app to interact with it. Everything was working perfectly, but now suddenly the login function is throwing a connection refused error along with the data. C ...

Unable to retrieve device UUID using capacitor/device on Android

I'm currently attempting to obtain the UUID of my devices so that I can send targeted notifications via Firebase. My front end and back end are connected, enabling the back end to send notifications to the front end using Firebase. However, all I am a ...

Generating a type definition from a JavaScript file

Looking to convert a .js file to a d.ts file, I've noticed that most resources on this topic are from 2 years ago How do you produce a .d.ts "typings" definition file from an existing JavaScript library? My question is, after 2 years, is there a simp ...

The communication between the Next.js and Node.js servers is being obstructed as the request body fails

Could you lend me a hand with this issue? Here is the function being called: function apiCreate(url, product) { console.log('Posting request API...' + JSON.stringify(product) ); fetch(url, { dataType: 'json', method: 'post ...

Expanding the global object in ES6 modules to include TypeScript support for extensions like `Autodesk.Viewing.Extension`

I created a custom forge extension and now I am looking to incorporate typescript support as outlined in this blog post. However, I am facing an issue where typescript cannot locate the objects like Autodesk.Viewing.Extension and Autodesk.Viewing.ToolInter ...

When the tab is switched, the URL remains the same. However, if the URL is changed,

The tabs are changing content but the URL is not being updated. Please refer to this link for a clearer explanation of my issue: https://codesandbox.io/s/mui-tabs-58y4gk Whenever I click on a tab, the URL should change accordingly (for example, clicking ...

When navigating to a non-existent path or encountering an error page, Next.js automatically initiates a hard reload

When navigating to an undefined path or encountering an error page in Next.js, a hard reload occurs which resets my context to its default state. This means the value stored in the userProfile state variable reverts back to null. In my layout that include ...

Error encountered: No matching overload found for MUI styled TypeScript

I am encountering an issue: No overload matches this call. Looking for a solution to fix this problem. I am attempting to design a customized button. While I have successfully created the button, I am facing the aforementioned error. Below is my code ...

How can Karma unit tests with Jasmine in a TypeScript Node project accurately measure code coverage, even with external dependencies?

We have a unique situation with the code coverage of our project involving a node dependency. It's important to note that the npm dependency source code is actually part of our project, as we are responsible for its development and publication. Here&a ...

Tips for implementing a unique design within a nested component using NextJS App Router

https://i.stack.imgur.com/EaYOG.png Here is the structure of my app router: The root layout must be shared with everyone. However, within the login component, there is another layout.jsx that should not share the root layout but override it and use the l ...

Guide on transitioning a client-side "authentication validation" setup to the updated app routing system

After successfully stabilizing the app router, I made the decision to transition from the old pages folder. Prior to implementing the app router, it was common practice to utilize the getserversideprops function to verify if a user is logged in. If not, t ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

Using an External JavaScript Library in TypeScript and Angular 4: A Comprehensive Guide

My current project involves implementing Google Login and Jquery in Typescript. I have ensured that the necessary files are included in the project: jquery.min and the import of Google using <script defer src="https://apis.google.com/js/platform.js"> ...

Access information from a different component within the route hierarchy

Suppose you have three components named A, B, and C with the following routing direction: A -> B -> C To retrieve data from the previous component (going from C to get data from B), you can use the following lines of code: In Component C: private ...