How to Use an Express Router Within the Cloud Function Developing Environment.
When I change my express project into a firebase compatible one, I’ve faced an issue with express routing.
So, I posted questions into Stackoverflow.
And also, I read this medium post.
But, David’s tutorial clip was really helpful. I’d watched it before, but when I watch this again, I realized my side problem.
here is /functions/index.js
My purpose is this.
I want to make the routes to separate several module files using express.router()
My previous fault was, I put the parameter express.router() into onRequest method. but you have to put the app — express() onto onRequest parameter.
And you can keep your route separation using
app.use("/your_route", your_router_module)
And here is /functions/api.js
here, several paths were prepared for testing. But if you want to call the function, You might have to use this condition block
You need the full path. It is ugly, isn't it?
But, if you add rewrites on your firebase.json, It doesn’t need.
You can write like this also,
"rewrites": [{
"source": "/api",
"function": "api"
}]/* most tutorial only said this. but I also faced to the problem with deeper endpoint. */
But in this case, you can’t access deeper. You can only access this [host:port/api] one endpoint. You cannot access to [host:port/api/data] or [host:port/api/v2/data]
so, you should use this.
"rewrites": [{
"source": "/api/**",
"function": "api"
}]
You granted to access any deep endpoint. but, keep in mind, now, you can’t access to the [host:port/api] but you can on [host:port/api/]
Don’t be confused, you did
app.use("/api", apiRoute)
So,
router.get("/api/user/data", (req, res) => {
res.send(`this is /api/user/data`)
})
in here, the first “/api” subpath was skipped.
You can also extend your module by extending your rewrites rules.
firebase.json
/functions/user.json [new file]
Result
You can separate your modules with the basic express router with no further integrating ways by firebase.
And you don’t need to worry about after deploy. There is no difference with the local environment. You don’t have to change something for deploying.
It works.