Search code examples
javascriptnode.jsfirebasegoogle-cloud-functions

Add middleware to all firebase functions in one line / function


In express you can add middleware such as app.use(cors()) which adds it to all of the endpoints, however I can't find something similar in firebase examples. Here is the example (see below) of how to apply it in every function. However I want to apply the middleware (cors or other) globally, as I have many functions.

import * as cors from 'cors';
const corsHandler = cors({origin: true});

export const exampleFunction= functions.https.onRequest(async (request, response) => {
       corsHandler(request, response, () => { return handler(req, res) });
});

What is the equivalent of app.use() in firebase? Is adding and express server the only option?


Solution

  • Use currying to create a handler, you have to repeat it across all the functions, but it's easier than writing the middleware each time:

    const applyMiddleware = handler => (req, res) => {
      return cors(req, res, () => {
        return handler(req, res)
      })
    }
    exports.handler = functions.https.onRequest(applyMiddleware(yourHandler))
    

    Edit, an example of a more complex middleware:

    const applyMiddleware =
      (handler, { authenticatedRoute = false } = {}) =>
      (req, res) => {
        if (authenticatedRoute) {
          const isAuthorized = isAuthenticated(req)
          if (!isAuthorized) {
            return res.status(401).send('Unauthorized')
          }
        }
        return cors(req, res, () => {
          return handler(req, res)
        })
      }
    exports.handler = functions.https.onRequest(
       applyMiddleware(yourHandler, { authenticatedRoute: true })
    )