Skip to content

Instantly share code, notes, and snippets.

Last active August 14, 2021 18:38
What would you like to do?
Firebase Functions Middleware Approach

Firebase Functions Middleware Approach

Initially, tried using the express-cors way but ended up causing the firebase functions https to be overwritten for some reason or another and had to rebuild everything and not do that. Instead, tried my own middleware that mimics how express works in how you call it.

I'm not trying to reuse existing middleware from express at this time but might be worth it at some point.

Use like so:

import {onRequest} from './middleware';
import {cors} from './cors';

export const helloWorld = onRequest(cors(), (req, res) => {
  res.send('hello world');
import {RequestHandler} from './middleware';
const cors = (): RequestHandler => {
const handler: RequestHandler = (req, res, next) => {
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
.set('Access-Control-Allow-Headers', '*')
.set('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
} else {
next && next();
return handler;
export {cors};
import * as functions from 'firebase-functions';
export type RequestHandler = (
req: functions.https.Request,
res: functions.Response,
next?: () => void
) => (Promise<void> | void)
const onRequest = (...fns: RequestHandler[]): functions.HttpsFunction => {
return functions.https.onRequest((req, res) => {
let counter = 0;
const next = () => {
if (counter > fns.length) {
fns[counter - 1](req, res, next);
export {onRequest};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment