Prerequisites
You need to know how to deal with nodejs and express framework to get the most out of this post.
What's Firebase Cloud Functions
Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your JavaScript or TypeScript code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers.
Initialize your nodejs project
- you need to create new firebase project.
- install firebase CLI
npm install -g firebase-tools
then install firebase functions and admin.
npm install firebase-functions@latest firebase-admin@latest --save
3.Run firebase login
to log in via the browser and authenticate the firebase tool.
then Run firebase init functions
and choose javaScript as your language.
after this commands your project will be successfully structured.
Let's start our coding journey
-now you need to import firebase functions and express framework.
- in your
index.js
add the following lines
const functions = require('firebase-functions');
const express = require('express');
const app = express();
create our new route by create new user file then create
user-route.js
in your
user-route.js
add the following lines
const express = require('express');
const router = express.Router();
router.get('/' , (req , res) =>{
return res.status(200).json('hello from user route');
});
module.exports = router;
- then we need to link our new route with express
- in
index.js
add the following lines
const userRoute = require('./user/user-route');
app.use('/user',userRoute);
- the final step in our code is linking express routes with firebase cloud functions in
index.js
exports.app = functions.https.onRequest(app);
- you now can emulate your cloud functions by using the following command
firebase emulators:start
- output will be
Resources
and That's it for this post, I hope you've learned something new, please drop me a comment if you didn't understand something, I also love to hear suggestions for improving, so if you have any, please drop me a comment.
Top comments (2)
I have multiple rest api -s (get post delete ...) from users and products,
how do I access all of them
index.js in functions
my app.js
my company.js
how do i get all of this routs
I am able to get just
app.get('/', (req, res) => {
res.send('Heloo ti Invest4You doslo je dop app.js');
} )
i need to get
app.use('/api/v1/companies', companyRouter);
app.use('/api/v1/users', userRouter);
please help
tnx
try this,
differentiate your apis and put in files,
then in require method, put path of your file,
example:-