Error encountered in NextJS API: "TypeError: res.status is not a function"

Background

In my development environment, I am using NextJS v11.1.1-canary.11, React v17.0.2, and Typescript v4.3.5.

To set up a basic API endpoint following the guidelines from NextJS Typescript documentation, I created a file named login.tsx in the pages/proxy folder with a simple API code snippet:

import type { NextApiRequest, NextApiResponse } from 'next'

export default function Login(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ name: 'John Doe' })
}

The Issue

Upon calling the API endpoint, an error is triggered :

TypeError: res.status is not a function
    at Login (C:\wamp64\www\project-front\.next\server\pages\proxy\login.js:19:7)

You can find the full stacktrace here.

Despite researching extensively, I have been unable to locate any similar cases on Google or Stackoverflow. As a newcomer to NextJS, it's possible that I am overlooking something. Is there anyone who might have insights into what I may be doing incorrectly?

Answer №1

Your demonstration is effective.

To resolve this issue, simply move your login.ts file to the directory pages/api/{whatever_you_want}

Please refer to the following documentation:

Any file located within the pages/api folder will be treated as an API endpoint (mapped to /api/*) and will not impact your client-side bundle size since they are server-side only bundles.

Answer №2

My experience was quite similar - the issue stemmed from my configuration of the runtime to use "experimental-edge".

If you simply remove or comment out that line, it should resolve the problem. It seems like a bug in the canary version.

// Check next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    appDir: true,
    transpilePackages: ["ui"],
    // runtime: "experimental-edge",
  },
};

Answer №3

If you are utilizing App Router and need to send back JSON data, take a look at the updated code snippet from Matei:

"use server";

import { NextRequest, NextResponse } from "next/server";

async function GET(req: NextRequest) {
  return NextResponse.json(
    { key: "value" },
    {
      status: 200,
    }
  );
}

export { GET };

Answer №4

In the case of employing the App Router, the expected response should be:

"use server";

import { NextRequest } from "next/server";

async function GET(req: NextRequest) {

    return new Response("Hello", {
        status: 200
    })
}

export { GET }

Answer №5

Make sure to always check the order of your input parameters as (req, res):

// Incorrect ❌
// This will result in a `TypeError: res.status is not a function` error
export default function Login(res, req) {
   ...
   res.status(200).json({ success: "ok" })
}

// Correct ✅
export default function Login(req, res) {
   ...
   res.status(200).json({ success: "ok" })
} 

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

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

Having trouble importing the hash-set module in TypeScript/SystemJS?

In the midst of developing an Aurelia project with TypeScript to generate JavaScript, I decided to incorporate another custom library called 'hash-set' (installed using jspm install npm:hash-set --save). However, I encountered difficulties in act ...

In the world of GramJS, Connection is designed to be a class, not just another instance

When attempting to initialize a connection to Telegram using the GramJS library in my service, I encountered an error: [2024-04-19 15:10:02] (node:11888) UnhandledPromiseRejectionWarning: Error: Connection should be a class not an instance at new Teleg ...

The wrong parameter is used to infer the generic function type argument in TypeScript

When using the code snippet below and not explicitly specifying T at function call, such as getOrPut<Item>(...), it is inferred from the create parameter. However, this can lead to the created item type being incompatible with the obj dictionary, as ...

Unusual Behavior of *ngIf and jQuery in Angular 5: A curious case

I'm encountering a strange issue when using the expand-collapse feature of Bootstrap 4 with *ngIf for expansion and collapse. I noticed that the jQuery doesn't work when *ngIf is used, but it works fine when *ngIf is removed. HTML: <div cla ...

React TypeScript with ForwardRef feature is causing an error: Property 'ref' is not found in type 'IntrinsicAttributes'

After spending a considerable amount of time grappling with typings and forwardRefs in React and TypeScript, I am really hoping someone can help clarify things for me. I am currently working on a DataList component that consists of three main parts: A Co ...

WebStorm is having difficulty identifying the Next.js project

I'm running into an issue with a React Next.js project that was previously functioning properly, but now it's having trouble recognizing the project and files. This means I can't search for files or find information within them. Even after ...

Exploring the power of SCSS modules within Next.js

In my next.js project, I am using next-int to set up languages. Typically, I have components with a module.scss file each. However, I want to avoid duplicating my scss files for styling the Arabic version of my site. The main differences come down to align ...

When the webpage first loads, the CSS appears to be broken, but it is quickly fixed when

Whenever I build my site for the first time, the CSS breaks initially, but strangely fixes itself when I press command + s on the code. It seems like hot reloading does the trick here. During development, I can temporarily workaround this issue by making ...

Unsure about module loading with system.js and navigating Typescript

I am currently in the process of transitioning an ASP.Net MVC application to Angular2, and I've encountered some perplexing behavior that I can't seem to grasp. Within my Angular2 app, I have a separate Layoutview that allows me to switch betwee ...

Tips for showcasing the information from a JSON document in React

I have a JSON file stored statically in my public directory and I'd like to show its content within a React component (specifically NextJS). The goal is to simply render the JSON as it is on the page. import data from '../../public/static/somedat ...

Utilizing string literals as index signatures

I've created a code snippet called MyTest that maps over an object: type MyTest<T> = { [P in keyof T]: T[P]; }; type Result = MyTest<{hello: 'world', foo: 2}>; // ^? type Result = { hello: 'world', foo: 2 } ...

What is the purpose of running tsc --build without any project references?

Out of curiosity, I decided to experiment by executing tsc --build on a project without any project references. Surprisingly, the command ran smoothly and completed without any issues. I expected there to be a warning or error since the build flag is typic ...

"In Typescript, receiving the error message "Attempting to call an expression that is not callable" can be resolved

I am in the process of creating a function that matches React's useState signature: declare function useState<S>( initialState: S | (() => S), ): [S, React.Dispatch<React.SetStateAction<S>>]; Below is an excerpt from the functi ...

Issue encountered with the signature provided for a Safe API POST request

Watch this demonstration video of the issue at hand: I have created a signer using my Metamask Private Key and generated a signature from it as shown below: const signer = new ethers.Wallet(PRIVATE_KEY as string, provider) const safeInstance = new ethers. ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

"Customizing the template of the Angular Material 2 datepicker: A step-by-step

Looking to make changes to the templates of the angular 2 material date-picker? These templates are located within various internal components in @angular/material/esm5/datepicker.es5.js. One option is to directly modify the template in the node package, ...

Retrieving information from the Dog API using axios and storing the results in a fresh array

Currently, I am working on a NextJS app using Typescript. My issue lies in the functionality aspect of the application. I am utilizing the Dog API to retrieve all the breeds names and store them in a new array of arrays. Each sub-array contains the breed a ...

Finding it challenging to adapt an AngularJs component-based modal to TypeScript

When creating an AngularJS component in JavaScript and displaying it as a modal using ui-bootstrap, you need to pass bindings that the modal instance can use for dismissing or closing itself: app.component("fringeEdit", { controller: "FringeEditCont ...

Issue with Angular 2 Routing: Unable to find a matching route

Currently, I'm in the process of developing an Angular 2+ application that requires routing. One of the requirements is for the color scheme of the entire app to change based on a URL parameter input. In my app.module.ts file, I have the following co ...