Many Koa.js users encounter some problems with Firebase Functions during parse bodies using koa-bodyparser.
So, I'd like to share how to solve this problem and help who haven't come across this yet 🧙🏻♂️❤️.
Before starting there are some terms that should be clarified for newcomers.
-
Koa.js
is a very minimal and elegant Node.js web framework developed by the team behind Express.js. -
Firebase Functions
is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. -
koa-bodyparser
A body parser for Koa, based on co-body. support json, form and text type body.
Note: The current version of koa-bodyparser is 4.3.0
You should know that Firebase actually parses the body. (see more here 👀)
Therefore the module getting confused deals with ctx.request.body
and ctx.req.body
and an error appears here.
The quick solution is to use ctx.req.body
because it's already parsed. 😅
Also, you can create a small middleware function to support already parsed bodies. (ref to this code 📌)
// Import koa-bodyparser module const bodyParser = require('koa-bodyparser'); // Middleware for Koa@2.x.x function hybridBodyParser (opts) { const bp = bodyParser(opts); return async function (ctx, next) { ctx.request.body = ctx.request.body || ctx.req.body; return bp(ctx, next); } } // Usage app.use(hybridBodyParser());
Top comments (0)