DEV Community

Cover image for Using Firebase Cloud Functions with Nodejs and Express
Sherif Shahin
Sherif Shahin

Posted on • Edited on

Using Firebase Cloud Functions with Nodejs and Express

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

  1. you need to create new firebase project.
  2. install firebase CLI
npm install -g firebase-tools
Enter fullscreen mode Exit fullscreen mode

then install firebase functions and admin.

npm install firebase-functions@latest firebase-admin@latest --save
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode
  • 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;
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode
  • the final step in our code is linking express routes with firebase cloud functions in index.js
exports.app = functions.https.onRequest(app);
Enter fullscreen mode Exit fullscreen mode
  • you now can emulate your cloud functions by using the following command
firebase emulators:start
Enter fullscreen mode Exit fullscreen mode
  • output will be Image description

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)

Collapse
 
ture23 profile image
ture23

I have multiple rest api -s (get post delete ...) from users and products,
how do I access all of them

index.js in functions

import functions from 'firebase-functions';
import app from '../app.js';


export const invest = functions.https.onRequest(app);

Enter fullscreen mode Exit fullscreen mode

my app.js

import express from 'express';
import cors from 'cors';
import morgan  from 'morgan';
import rateLimit  from 'express-rate-limit';
import helmet  from 'helmet';
import mongoSanitize  from 'express-mongo-sanitize';
import xss  from 'xss-clean';
import hpp from 'hpp';
import path  from 'path'

import AppError from './utils/appError.js';
import companyRouter from './routs/company.js'
import userRouter from './routs/user.js'


const app = express();
app.use(cors());

// 1) GLOBAL MIDDLEWARES
// Set security HTTP headers
app.use(helmet());

// Development logging
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}
// app.use(bodyParser({
//   json: { limit: '50mb', extended: true },
//   urlencoded: { limit: '50mb', extended: true }
// }));
// Limit requests from same API
const limiter = rateLimit({
  max: 100,
  windowMs: 60 * 60 * 1000,
  message: 'Too many requests from this IP, please try again in an hour!'
});
app.use('/api', limiter);

// Body parser, reading data from body into req.body
app.use(express.json({ limit: '250kb' }));

// Data sanitization against NoSQL query injection
app.use(mongoSanitize());

// Data sanitization against XSS
app.use(xss());

// Prevent parameter pollution
app.use(
  hpp({
    whitelist: []
  })
);

// Serving static files
// app.use(express.static(`${__dirname}/public`));

// Test middleware
app.use((req, res, next) => {
  req.requestTime = new Date().toISOString();
  // console.log(req.headers);
  next();
});
// app.use(express.static(path.resolve('../client/build')));

// app.get('*', (req, res) => {
//   res.sendFile(path.resolve('../client/build', 'index.html'));
// });
// // 3) ROUTES
app.use('/api/v1/companies', companyRouter);
app.use('/api/v1/users', userRouter);
app.get('/', (req, res) => {
  res.send('Heloo ti Invest4You doslo je dop app.js');
} )
// app.use('/api/v1/reviews', reviewRouter);

app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

// app.use(globalErrorHandler);

export default app;

Enter fullscreen mode Exit fullscreen mode

my company.js

import express from 'express';

import {getAllCompanies, getOneCompany, createCompany, updateCompany, deleteCompany, likeCompany, newPrice, GetAllPrices} from '../controllers/company.js'
import { protect } from '../controllers/auth.js'
import { createNews, getAllNews } from '../controllers/newsController.js';

const router = express.Router();


router.get('/', getAllCompanies);
router.get('/ir', getAllNews);
router.get('/myAccount', GetAllPrices);
router.get('/:id',  getOneCompany);
router.post('/', createCompany);
router.post('/myAccount',  newPrice);
router.post('/ir',  createNews);
router.patch('/:id/likeCompany',protect, likeCompany);
router.patch('/:id', updateCompany);
router.delete('/:id', deleteCompany)

export default router;
Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
kafeel_ahmad profile image
Kafeel Ahmad (kaf shekh)

try this,
differentiate your apis and put in files,
then in require method, put path of your file,
example:-

require("./app/routes/auth.routes")(app);
require("./app/routes/student.routes")(app);
Enter fullscreen mode Exit fullscreen mode