Skip to content

modify raw body in api route #27702

Answered by leerob
macrozone asked this question in Help
Aug 2, 2021 · 2 comments · 6 replies
Discussion options

You must be logged in to vote
import type { NextApiRequest, NextApiResponse } from 'next';
import type { Readable } from 'node:stream';

export const config = {
  api: {
    bodyParser: false,
  },
};

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

export default async function (req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const buf = await buffer(req);
    const rawBody = buf.toString('utf8');

    res.json({ rawBody });
  } else {
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

Replies: 2 comments 6 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
6 replies
@activenode
Comment options

@darklight9811
Comment options

@leerob
Comment options

@asongate
Comment options

@marcelo-albuquerque
Comment options

Answer selected by leerob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
8 participants