Advaned URL Routing in Google Cloud Functions for Firebase

If you're as in love with Google Cloud Functions for Firebase as I am, you're likely a bit sad to hear that every HTTPS function ties to one specific URL.

For example, by default, a function named date ties to a location like...

https://us-central1-<project-id>.cloudfunctions.net/date  

This is fine for simple functions, but what if you want complete control over your URL routing?

Well we got you, fam. You can actually pass in a normal Express app to handle your function calls.

const functions = require('firebase-functions');  
const app = require('express')();

app.get('/', (req, res) => {  
  res.send(`Root page`);
});

app.get('/second', (req, res) => {  
  res.send(`Sub function`);
});

app.get('/hello/:name', (req, res) => {  
  res.send(`Hello ${req.params.name}`);
});

// We name this function "route", which you can see is 
// still surfaced in the HTTP URLs below.
exports.route = functions.https.onRequest(app);  

Now this "single function" can actually call many different paths.

# curl https://YOUR_FUNCTIONS_URL/route/
Root page

# curl https://YOUR_FUNCTIONS_URL/route/second
Sub function

# curl https://YOUR_FUNCTIONS_URL/route/hello/abe
Hello abe  

And yes this works with middleware, too.

Awesome, right? Happy functioning!


Follow me on Twitter