Next.js Discord

Discord Forum

Error: ⨯ TypeError: res.status is not a function

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
/api/dirs/route.ts
import fs from "fs";
import path from "path";
import type { NextApiRequest, NextApiResponse } from "next";

const GET = (req: NextApiRequest, res: NextApiResponse) => {
  const directoryPath = "G:\\";
  if (req.method == "GET") {
    try {
      const files = fs
        .readdirSync(directoryPath, { withFileTypes: true })
        .filter((dirent) => dirent.isDirectory())
        .map((dirent) => dirent.name);
      console.log(files);
      res.status(200).json({ files });
    } catch (error) {
      res.status(500).json({ error: "Unable to retrieve directory contents" });
    }
  }
};

export { GET };

/src/app/dirs/page.tsx

"use client";

import { Button } from "@nextui-org/button";
import { useEffect, useState } from "react";

export default function Dirs() {
  const [dirs, setDirs] = useState<string[]>([]);

  useEffect(() => {
    fetch("/api/dirs", { method: "GET" }) // <--- this is where the error occurs
      .then((response) => response.json())
      .then((data) => setDirs(data.files))
      .catch((err) => console.error(err));
  }, [dirs]);

  const listItems: any[] = [];
  dirs.forEach((file) => {
    console.log(file);
    listItems.push(<li key={file}>{file}</li>);
  });

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div>
        <Button>Click me</Button>
        <ul>{listItems}</ul>
      </div>
    </main>
  );
}

⨯ TypeError: res.status is not a function
Answered by Giant panda
API routes are a pages router feature. In the app router they are called route handlers now.
View full answer

12 Replies

Giant panda
Your issue is that you haven't read the docs how responses are done in route handlers. The syntax has changed compared to the pages router and there is no more res parameter.
Transvaal lionOP
so its the Response.status now?
but why do the NextApiRequest types exist then
Giant panda
The signature has changed, that doesn't mean the types are useless now.
Transvaal lionOP
Giant panda
These are the docs for the pages router, not the app router.
Transvaal lionOP
wydm, it says api routes, my thing is an api route
Giant panda
Which is also noticeable because the example exports a default handler and not named functions like GET
See the select box in the top left
Transvaal lionOP
:face_palm:
Giant panda
API routes are a pages router feature. In the app router they are called route handlers now.
Answer
Transvaal lionOP
okay thats alot better, tysm homie