I'm trying to both validate and use the body response in a Lemonqueezy webhook request in NextJS
I'm getting the signature validation to work, but the body object is then empty(presumably consumed by the signature validation).
I tried cloning the request, but this doesn't seem to do anything.
How do I get to validate the signature AND use the request body in NextJS?
Here's my code
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import crypto from "crypto";
import getRawBody from "raw-body";
import clone from "clone-deep";
import { json } from "micro";
export const config = { api: { bodyParser: false } };
type Data = { message: string };
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
if (req.method === "POST") {
const clonedReq = clone(req);
const rawBody = await getRawBody(clonedReq);
const hmac = crypto.createHmac(
"sha256",
process.env.LEMONSQUEEZY_SIGNING_SECRET
);
const digest = Buffer.from(hmac.update(rawBody).digest("hex"), "utf8");
const signature = Buffer.from(
req.headers["x-signature"].toString() || "",
"utf8"
);
const valid = crypto.timingSafeEqual(digest, signature);
console.log("valid", valid);
if (valid) {
const body = await json(req);
console.log("body", body);
res.status(200).json({ message: "Success" });
} else {
res.status(500).json({ message: "Illegal method" });
}
} else {
res.status(500).json({ message: "Illegal method" });
}
}