@golevel/nestjs-webhooks `RawBodyMiddleware` and `JsonBodyMiddleware` incompatible with @nestjs/platform-fastify
See original GitHub issueThe middlewares use the Express req
and res
objects.
I spent a good amount of time trying to figure this one out last night, because Stripe explodes on you if the webhook payload format isn’t exactly how it wants =/
https://github.com/fastify/help/issues/158 https://github.com/fastify/fastify/issues/1965
According to this thread, you can set this up in Fastify like this:
fastify.addContentTypeParser(
'application/json',
{ parseAs: 'buffer' },
function (req, body, done) {
try {
var newBody = {
raw: body
}
done(null, newBody)
} catch (error) {
error.statusCode = 400
done(error, undefined)
}
}
)
fastify.post('/stripe/myhook', {
handler: async (req, res) => {
const sig = req.headers['stripe-signature']
const webhookSecret = 'whsec_d....'
const event = stripe.webhooks.constructEvent(req.body.raw, sig, webhookSecret)
.....
}
})
So I attempted this in a hacky way and still no luck. It seems setting req.body
, req.rawBody
, and req.raw
does not work. And this is a poor implementation anyways because it’s global.
If anyone has figured this out, would be great info + maybe I can PR a second set of middlewares that support @nestjs/platform-fastify
.
import { AppModule } from './app.module'
import { NestFactory } from '@nestjs/core'
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify'
import fastify from 'fastify'
async function bootstrap() {
const fastifyInstance = fastify()
fastifyInstance.addContentTypeParser(
'application/json',
{ parseAs: 'buffer' },
function (req, body, done) {
try {
console.log('Parsing req with body:', body)
var newBody = {
body,
rawBody: body,
raw: body
}
console.log('Parsed body result:', newBody)
done(null, newBody)
} catch (error) {
error.statusCode = 400
done(error, undefined)
}
}
)
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(fastifyInstance as any), {
// Disable body parsing for Stripe webhooks to work properly. Needs raw request body.
bodyParser: false,
})
await app.listen(3001, '0.0.0.0')
}
bootstrap()
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:8 (2 by maintainers)
Top Results From Across the Web
No results found
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I solved it using fastify-raw-body
That’s how I managed to enable this plugin only on one route: