Closed ChiefORZ closed 1 month ago
Next.js's body parser does not support multipart/form-data
. Most frameworks do not out of the box either, so you need to use something like multer
to correctly parse the body as outlined here in the case of express.js.
Because, next.js route handlers do not have middleware, you'll need to define your own handler for that specific endpoint, call multer, then forward the request to the handler defined by createSingleRouteHandler
.
import multer from 'multer';
export const config = {
api: {
bodyParser: false,
},
};
const upload = multer();
export default async (req: NextApiRequest, res: NextApiResponse) => {
upload.none()(req, null, (error) => {
// req.body will now have the text fields
return createSingleRouteHandler(contract.endpoint, async (args) => ...)(req, res);
});
};
Describe the bug
We tried to create a contentType multipart/form-data contract:
In the request itself we are creating a new FormData instance that we pass to the fetch:
The request is done and the content-type headers are set correctly and the multipart/form-data body looks perfectly find, still the next api resolves in an error:
How to reproduce
git clone https://github.com/ChiefORZ/nextjs-ts-rest-headers-bug.git
cd nextjs-ts-rest-headers-bug
pnpm dev
open http://localhost:3000
-> POST /document response will fail with
Expected behavior
No response
Code reproduction
https://github.com/ChiefORZ/nextjs-ts-rest-headers-bug
ts-rest version
3.45.2