2

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?

Kevin Danikowski
  • 3,470
  • 4
  • 27
  • 59
  • Here is an official firebase functions sample that shows using express to handle the middleware. Export the express app and the function is public. https://github.com/firebase/functions-samples/blob/main/authorized-https-endpoint/functions/index.js – IcyIcicle May 31 '22 at 22:37

1 Answers1

5

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(handler))

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(handler, { authenticatedRoute: true })
)
Kevin Danikowski
  • 3,470
  • 4
  • 27
  • 59