loading...

Getting all 404s with your firebase functions?

splodingsocks profile image Murphy Randle ・2 min read

If you're using Firebase Cloud Functions and you get an error like this:

cannot GET null after trying to access your function in production, it’s probably because you’re using an Express app a the request handler, and the request object that firebase passes in has an empty string instead of a “/“ as the URL (when accessing the function name directly with no trailing slash).

The trick is to intercept the request and insert that “/“ before it gets handed to the Express app. I tried it as middleware for the app and it didn’t work.

Here’s the patch I have:

let firebasePathPatch: 'a => Express.App.t = [%bs.raw {|
  app => (req, res) => {
    // patch from https://github.com/firebase/firebase-functions/issues/27#issuecomment-292768599
    // https://some-firebase-app-id.cloudfunctions.net/route
    // without trailing "/" will have req.path = null, req.url = null
    // which won't match to your app.get('/', ...) route 
    if (!req.path) {
      // prepending "/" keeps query params, path params intact
      req.url = `/${req.url}`
    }
    return app(req, res);
  }
|}];

And that’s used like this:
Firebase.CloudFunctions.functions##https##onRequest(app |> firebasePathPatch);

The snippet above is in Reason, here's a version in JS:

let firebasePathPatch = app => (req, res) => {
    // patch from https://github.com/firebase/firebase-functions/issues/27#issuecomment-292768599
    // https://some-firebase-app-id.cloudfunctions.net/route
    // without trailing "/" will have req.path = null, req.url = null
    // which won't match to your app.get('/', ...) route 
    if (!req.path) {
      // prepending "/" keeps query params, path params intact
      req.url = `/${req.url}`
    }
    return app(req, res);
  }

// Used like this:
module.exports.foo = functions.https.onRequest(firebasePathPatch(app));

See more here: https://github.com/firebase/firebase-functions/issues/27

Discussion

markdown guide