#DELETED
1 messages · Page 1 of 1 (latest)
To get the raw request body in a middleware, you can use the following code snippet adapted from the Vercel guide (https://vercel.com/guides/how-do-i-get-the-raw-body-of-a-serverless-function). This example demonstrates how to convert a ReadableStream<Uint8Array> to a Buffer.
import type { Readable } from 'node:stream';
async function buffer(readable: Readable) {
const chunks = [];
for await (const chunk of readable) {
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
}
return Buffer.concat(chunks);
}
However, it's important to note that in Next.js Middleware, sending response bodies is not allowed. Middleware should only be used to rewrite, redirect, or modify the incoming request. You can read more about this in the Middleware Upgrade Guide (https://nextjs.org/docs/messages/middleware-upgrade-guide).
If you still need to process the raw request body, you might want to consider using Next.js API Routes (https://nextjs.org/docs/api-routes/introduction) instead of Middleware.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@finite depot kapa.ai is still learning and improving, please let us how it did by reacting below