Skip to content

Instantly share code, notes, and snippets.

@robvanderleek
Last active July 28, 2024 15:45
Show Gist options
  • Save robvanderleek/e5a83e4b676b20c376917f499bae8954 to your computer and use it in GitHub Desktop.
Save robvanderleek/e5a83e4b676b20c376917f499bae8954 to your computer and use it in GitHub Desktop.
Reading raw body content on Vercel

Reading raw body content on Vercel

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'});
}

Accessing the raw request body

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment