Home > Net >  Firebase functions parsing request body before I can handle it in Express
Firebase functions parsing request body before I can handle it in Express

Time:10-27

I'm trying to handle invalid requests in Firebase functions, so making a post request with invalid JSON, with the intent of handling it in express. but I get 400 error 'SyntaxError: Unexpected token a in JSON at position 20' before it even reaches express layer, and the worst thing is the function runs for 60 seconds untill it hits timeout error.

my function

import * as functions from 'firebase-functions';
import * as express from 'express';
import * as admin from 'firebase-admin';

admin.initializeApp();


const app = express();

app.use((err: any, req: any, res: any, next: any) => {
  res.json({ error: 'invalid request' });
  next(err);
});

app.post('/test', (req: any, res: any) => {
  res.json({ error: 'invalid request' });
  res.end();
  return;
});



const server = functions.runWith({ maxInstances: 100 }).https.onRequest(app);

export { server as api };

the invalid json,

{
    "es":"adfasdf"asdf
}

I suspect this has something to do with the https://firebase.google.com/docs/functions/http-events#read_values_from_the_request at "This parsing is done by the following body parsers:"

CodePudding user response:

Firebase Functions are built on top of the functions-framework-nodejs package (or at least, an internal variant of the same code).

Within that package, the body parsers you mention are injected. As you correctly surmised, these are indeed added before your code even gets the chance to execute.

As the error is internal to Firebase's operations, you will need to reach out to Firebase support directly.

  • Related