Firebase functions: koa.js server how to deploy - node.js

I already have an app written in MERN stack with koa server prepared build version. My main node file to run by node server.js command to start the whole app looks like this.
In every tutorial, I see that I need to add functions.https.request etc. in the beginning of coding (or at least to suppose doing it).
How could I host my app on firebase the same as I could on heroku - with whole server side?

It is possible to host Koa app using firebase functions, I figure it out after some Googling and analyzing.
This is a piece of code from my project, it is now hosted with firebase functions:
const Koa = require('koa');
const app = new Koa();
// ... routes code here ...
// This is just for running Koa and testing on the local machine
const server = app.listen(config.port, () => {
console.log(`HITMers-server is running on port ${config.port}`);
});
module.exports = server;
// This export is for Firebase functions
exports.api = functions.https.onRequest(app.callback());
You can see the docs and tutorial video for more information.
By the way, here is another example to deploy Koa to now.sh version 2.

You can actually skip the listen call entirely, and use app.callback().
This seems to make more sense than listening on a random port that never actually gets hit.
const functions = require('firebase-functions');
const app = new Koa();
... // set up your koa app however you normally would
app.use(router.routes());
module.exports.api = functions.https.onRequest(app.callback());

You can run an express application using firebase hosting to serve dynamic content via firebase functions. You cannot, however, use Koa.js currently. The functions.https.onRequest requires you to pass an HTTP request handler or an express app returned from express().
Here is the relevant article from Firebase about serving dynamic content from functions.
https://firebase.google.com/docs/hosting/functions
Here is a video tutorial from Firebase on using express.
https://www.youtube.com/watch?v=LOeioOKUKI8

To anyone looking for koa Google Cloud Functions, Here is my working version in typescript
import Koa from 'koa';
import Router from 'koa-router';
import type { HttpFunction } from '#google-cloud/functions-framework/build/src/functions';
const app = new Koa();
const port = process.env.PORT || 3001;
const router = new Router();
router.get('/', async (ctx) => {
ctx.body = 'Hello World!';
});
app.use(router.routes());
// For development on local
if (!isCloudFunctions()) {
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
}
export const helloWorldApi: HttpFunction = app.callback();
function isCloudFunctions(){
return !!process.env.FUNCTION_SIGNATURE_TYPE;
}
For deployment:
gcloud functions deploy test-koa-function --entry-point=helloWorldApi --runtime nodejs16 --trigger-http --allow-unauthenticated

You can't deploy and run an arbitrary node app on Cloud Functions. You have to make use of the different types of triggers that are defined by the product.
See the Cloud Functions for Firebase main page to see the list.
Cloud Firestore Triggers
Realtime Database Triggers
Firebase Authentication Triggers
Google Analytics for Firebase Triggers
Crashlytics Triggers
Cloud Storage Triggers
Cloud Pub/Sub Triggers
HTTP Triggers

Related

Firebase cloud functions emulator - how to connect node.js to emulator

I've installed firebase emulator to be able to develop some cloud function locally before deploy them.
Im reading this guide but I'm not sure how to proceed. The example use the import syntax but I need to write a node.js cloud function and I'm not sure how to proceed.
How I can correctly connect to the cloud functions emulator from my index.js file that will contain the needed logics?
At the moment my file looks like this:
const admin = require('firebase-admin')
const functions = require("firebase-functions");
const stripe = require('stripe')
admin.initializeApp()
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// functions.logger.info("Hello logs!", {structuredData: true});
// response.send("Hello from Firebase!");
// });
const db = admin.getDatabase()
What I need is to use stripe but to achive my scope I need to read from firebase realtime database first and I didn't setup that emulator but only the cloud functions one.
Any suggestion will be appreciated, thank you!

can i run a node function on a react app directly

I am making a react app where I need to fetch some data using an API.
I want to deploy this app with Netlify so I cannot use a backend. So, I wrote a Firebase Cloud Function to handle the fetching. However, Google wouldn't allow third-party API requests on the free plan.
So either I have to learn using AWS or I will write a backend and deploy using another service.
Honestly, I don't want to do either. So, my question is, can I call this node function directly inside my react app if so how and is it advisable, if not are there any other alternatives?
The function is something like this:
const functions = require("firebase-functions");
const League = require("leagueapiwrapper");
require("dotenv").config();
exports.getFavorites = functions.https.onCall(async (data, context) => {
try {
const LeagueAPI = new League(process.env.API_KEY, Region.TR);
...
The only thing that actually requires node is the leagueapiwrapper package. (Obviously I will get rid of firebase related stuff).

Node.js, Express.js, Angular.js: Hosting my own API

I am new to coding and I have a question about a small app that I created with angular.js that makes a post request to another express.js app.
It's a simple parentheses balance checker, you can find the whole code here:
https://github.com/OGsoundFX/parentheseschecker
The FrontEnd-Refactored folder contains the Angular.js app and the APItesting contains the express.js API.
The app is working, but I have only been using it locally. The API runs on localhost:3000 and the app on localhost:8080
But what if I want to make it public? How would I go about it? I don't really know where to start.
Where to host a node.js of express.js app. I read about AWS, would that be good, or are there better services?
I have a Wordpress website hosted on https://www.mddhosting.com/ but that wouldn't work, right?
My Angular app is calling the api locally at the moment, so I will probably have to change the API link that it is fetching:
ApiService.js
function ApiService($http) {
API = '//localhost:3000/parentheses';
this.getUser = (entry) => {
return $http
.post(API, { string: entry} )
.then(function (response) {
return response.data;
}, function (reason) {
// error
})
};
};
angular
.module('app')
.service('ApiService', ApiService);
In my API server.js
const http = require('http');
const app = require('./app')
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
I will definitely have to change API = '//localhost:3000/parentheses'; in my AngularJS app, but should I change const port = process.env.PORT || 3000; ?
I just need a little push start to help me clear some confusion.
Thanks!
Ensure you use application-level environment variables For example: To define the BASE_URL of your site for development and production separately. Doing so you don't have to make any configuration changes when you go live, it is a one-time process.
And if you are looking for free hosting services for pet projects Heroku is good and if you really want to make site go live for the end-users you may go for AWS EC2 instance or Heroku paid service both are good.

Node module doesn't work in Firebase hosting?

I have a Node server and use Firebase hosting. The server uses the Node module rss-to-json for parsing a RSS feed to JSON.
When I test the server on my machine, the request works, but when deploying it doesn't work. It just loads forever and gives:
"Error 503 first byte timeout"
My code:
const functions = require("firebase-functions");
const express = require("express");
const Feed = require("rss-to-json");
app.get("/feed", (req, res) => {
Feed.load("https://www.reddit.com/.rss", function(err, rss) {
res.send(rss);
});
});
exports.app = functions.https.onRequest(app);
Have tried:
Removed "node_modules" from "ignore" in firebase.json, but no luck.
Any ideas?
On the Spark payment plan, you can't make outgoing requests to services that aren't fully controlled by Google. If you want to do this, you'll have to upgrade your project to the Blaze plan. See the pricing page for more information.

Firebase Hosting with own server node.js

I have webapp with firebase database. I would like hosting the app on firebase. My app has own server nodejs and using websockets. How can I host my app on Firebase? And how can I run my own server on Firebase?
I think your question is quite simple. And the answer is also simple: no, you can't.
Firebase only serves static files. You need to try heroku, codeship, etc for that.
I'm not sure what exactly you are looking for. I'll assume it's one of these two:
you want to run the node.js scripts on Firebase's server
There is no way to run your own code on Firebase's servers.
you want to run the node.js scripts on your own server and have them interact with your Firebase data
Firebase has a node.js package that allows you to talk to its BaaS service from your own node scripts. See the node.js section in Firebase's quickstart and the npm package for Firebase.
You can use Google Cloud Functions to do most task processing in a serverless style: https://firebase.google.com/docs/hosting/functions
I'm using it to dynamically load javascript based on req.url.
With Firebase functions, yes you can. You can watch this tutorial from Google, it's very clear and easy to catch up.
Node.js apps on Firebase Hosting Crash Course - Firecasts
Firebase Hosting allows you to use Cloud Functions to perform server-side processing. This means that you can support dynamic generation of content for your Firebase Hosting site.
Documentation
Firebase Functions is the way to go.
Example:
Setup /index.js in your project with expressjs listening on port what ever you want. F.e. 3000
const app = express()
const port = 3000
...
app.get('/', (req, res, next) => {
... hier your code to handle request
})
...
app.listen(port, () => {
console.log(`app listening at port = ${port}`)
functions.logger.info("Application started", {structuredData: true});
})
Export your function with reference to express-app:
exports.api = functions.https.onRequest(app)

Resources