O rganization is key

If you’re reading this, I assume you’re as much of a neat-freak as I am! Most experienced Express developers won’t really need this part of the tutorial but I figured I’d include it anyways to keep the coverage level high.

Okay, we want to break out the /api/users endpoint into its own folder/file/both, that should be simple.

Let’s assume your Firebase Functions project has a simple project structure (as outlined by the Typescript setup post linked above):

.

+-- public/

+-- functions/

| +-- node_modules/

| +-- src

| | +-- index.ts

+-- database.rules.json

+-- firebase.json

Right now, all of our routes are being defined in index.ts (consider this file your api center-piece and is where all sub-routes will be defined, this is because of how Firebase Functions deployment works). But we want to start breaking that apart so that the file doesn’t explode in size. Let’s go ahead and create a folder for our users sub-route.

Lets introduce some new folders and file(s) into our project:

.

+-- public/

+-- functions/

| +-- node_modules/

| +-- src

| | +-- index.ts

| | +-- api/

| | | +-- users/

| | | | +-- index.ts

+-- database.rules.json

+-- firebase.json

Now any folder in the api folder is considered it’s own sub-route. Choose any directory structure you’d like, as long as you have an index.ts file that does not conflict with the one in the root of the src folder.

Now, lets open up functions/src/api/users/index.ts :

Simple /users route with only one match, emulating our getUser method.

Cool, we now have the router for our /users sub-route! Feel free to add as many sub-routes as you’d like to the /users sub-route, I just provided what we’ve been using in the example as a starting point ( getUser ). Let’s register it in the root of the API (the index.ts sitting in /functions/src).

Nice! Let’s fire up this API and see what url Firebase Functions generates for our endpoints.

Is there something wrong? Where’s the /users route? :(

It’s there! Remember what I said before, the exports.api = ... is where we tell Firebase Functions hey FF, I have a route named /api, send all those requests to my Express app instance, please and thank you so the route should be there as long as you didn’t mess anything up along the way.

Lets run make the following request and see what the response is:

Checkout the response:

You requested user with UID = 123