Skip to content

Instantly share code, notes, and snippets.

@sebringj
Last active August 14, 2021 18:38
Show Gist options
  • Save sebringj/64b2ce31ad61e2b96ad5ddc354149861 to your computer and use it in GitHub Desktop.
Save sebringj/64b2ce31ad61e2b96ad5ddc354149861 to your computer and use it in GitHub Desktop.
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) => {
res
.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') {
res.status(204).send('');
} 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 = () => {
counter++;
if (counter > fns.length) {
return;
}
fns[counter - 1](req, res, next);
};
next();
});
};
export {onRequest};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment