Currently, I am utilizing next-connect in conjunction with next.js and typescript. My aim is to develop a middleware that can append additional fields to the request object and deduce the new request type. The following code snippet showcases this:
// multipart middleware
export type NextApiRequestMultipart = NextApiRequest & {
files: Files;
fields: Fields;
};
export function multipart(
config?: Options
) {
return async (
req: NextApiRequest,
res: NextApiResponse,
next: NextHandler
) => {
const { files, fields } = await parseForm(req, config);
(req as NextApiRequestMultipart).files = files;
(req as NextApiRequestMultipart).fields = fields;
return next();
};
}
export router().post(
multipart({ multiples: false }),
async (req, res) => {
// To access properties without statically typing the request
const { files, fields } = req;
}
);
Access the StackBlitz repository for the code: here