Vercel is a powerful platform for hosting serverless functions. A typical serverless function (in TypeScript) on Vercel looks like this:
async function (request: VercelRequest, response: VercelResponse) {
response.status(200).json({message: 'hello world'});
}
Vercel automagically extracts the body from an HTTP request and converts it to a JSON object, available as: request.body
.
However, sometimes it's necessary to access the raw HTTP body data (for me that use case was implementing a GitHub webhook
that uses the Probot library).
It took me quite some time to figure out how to read the raw body content in a serverless Vercel function. After some trial and error I got it to work by first disabling the automated Vercel body parser:
export const config = {
api: {
bodyParser: false
}
};
Next, a small utility function is needed to read the complete body from an HTTP request:
function getBody(request: VercelRequest): Promise<string> {
return new Promise((resolve) => {
const bodyParts: Uint8Array[] = [];
let body;
request.on('data', (chunk) => {
bodyParts.push(chunk);
}).on('end', async () => {
body = Buffer.concat(bodyParts).toString();
resolve(body)
});
});
}
And finally, this function can be used to read the raw body:
async function (request: VercelRequest, response: VercelResponse) {
const body = await getBody(request);
response.status(200).json({body: body});
}
To see a full implementation of the code snippets above, take a look at this GitHub webhook.