'how to strongly type body of NextApiRequest in Nextjs [duplicate]

wondering how to define the type of body of an API POST Nextjs route in order to benefit from typesafety ? In the NextApiRequest, body is defined as "any" and NextApiRequest is not generic

using as force the type but this is not clean at all

running NextJs12 and typescript 4.4.4

import { NextApiRequest, NextApiResponse } from "next";

interface IBody {
  test: string;
  value: number;
}

const handler = async (
  req: NextApiRequest, <-- whish to have something here like NextApiRequest<TQuery, TBody,..>
  res: NextApiResponse
): Promise<void> => {
  const { body } = req;
  console.log(body as IBody); <--this is not safe at all

  res.status(200).json({ text: "Hello" });
};

export default handler;


Solution 1:[1]

You can use TypeScript Omit to replace the body of the request with a custom type.

type Override<T1, T2> = Omit<T1, keyof T2> & T2;
    
export type MyCustomRequest = Override<NextApiRequest, { body: MyCustomRequestBody }>
    
export type MyCustomRequestBody = {
  myCustomField: string
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Edmonds