Home > front end >  An argument for 'body' was not provided for send() \ json() in Next.js's API, with T
An argument for 'body' was not provided for send() \ json() in Next.js's API, with T

Time:05-21

I'm using an API route in Next.js. In the 'api' folder, my 'file.tsx' contain the following:

import type { NextApiRequest, NextApiResponse } from "next";
const someFunction = (req: NextApiRequest, res: NextApiResponse<data>) => { the rest of the code... }

Everything does work. But, regarding the following line:

res.status(200).send();

send() is highlighted and I get the following TypeScript error:

Expected 1 arguments, but got 0.ts(2554) utils.d.ts(182, 25): An argument for 'body' was not provided.

Following the docs (https://nextjs.org/docs/api-routes/response-helpers), I tried adding an argument like res.status(200).send({key: "value"}), or res.status(200).send("string") or both with json() instead of send().

I even copied the exact examples from the docs, but still this error persist. The only thing that cleared the error (as a test) was changing the typing - but naturally, this is undesirable, as the error is probably there for a reason.

Am I missing something here?

CodePudding user response:

There are a couple of things going on here. For the first error, Typescript is complaining that no argument for 'body' was provided. This error is pretty straightforward as you already know. The other error comes from the type of response that is already defined for you:

res: NextApiResponse<Data>

Where the Data type is defined as:

type Data = {
  name: string;
};

Which is a an object with a name property that is of type string.

So, if you want to send a plain string then, you'll need to modify the type to this:

type Data = string;

You could also define it directly in the response, like this:


const someFunction = (req: NextApiRequest, res: NextApiResponse<string>) => {
  return res.status(200).json("hello");
};

export default someFunction

In any case, you need to keep in mind that Typescript requires you to be explicit of what type of data you're sending as a response. The whole point of having Typescript in a project is to prevent errors by adding type safety checks to the code.

See Everyday Types to learn more.

  • Related