Express Routing with Google Cloud Functions
Underneath it all, Google Cloud Functions written in Node uses the minimalist web framework Express via the Functions Framework.
With a few lines of Node, we can use extra features of Express like routing URLs to multiple endpoints via Express routing. This means using routing requests to URLs like /users
,/users/{id}
. In this post, we’ll learn how to do that!
Routing refers to how an application’s endpoints (URIs) respond to client requests.
Each route can have one or more handler functions, which are executed in order when the route is matched.
Why Does This Matter?
Using routing helps build logical, RESTful web applications. Rather than handling service routing logic with if
/else
conditional statements or switch
statements, we can leverage Express’s advanced yet simple routing feature!
I think it’s best illustrated with an example comparison:
Functions Without Express Routing — ❌
For a “Hello World” application, having a large function handler is acceptable. However, after your application evolves, you might find yourself doing this…
With your URL handlers in a separate file:
As you can see, we’re creating a potentially messy situation with our req.url.split('/')[1]
. In fact, this implementation is limited to only handle one level of path routing. We could have routing cases that overlap each other. Could we avoid using a switch
statement?
That’s where Express Routing comes in…
Functions With Express Routing — ✅️
Express routing comes built-in with the express
module, making it easy to integrate with the Functions Framework.
To get started, first explicitly install express
:
npm i express
In fact, your functions are already using express with the Functions Framework (whether you know it or not), so you aren’t adding an extra dependancy.
Then, separate out your methods into separate express
apps. This is called application-level middleware.
Here, we’ll show the same code as above, but using basic Express Routing instead of a switch
statement:
Here we are explicitly creating an express
object and using app.use
to define a routing function as middleware. We can easily specify URL path parameters like :id
that will be available in our handler under req.params.id
. Now that you’ve defined the express
object, you can also look into using other middleware like parsing cookies, serving static content, etc.
And that’s how you can use Express Routing with the Functions Framework!
Thanks for reading.
Got a question about using the Node Functions Framework?
Give us feedback by creating a new issue on GitHub! We are building more documentation on how to use the Functions Framework like using Docker and using Cloud Events.
Learn more about the Functions Framework!
Check out these other relevant resources: