Firebase Functions onCall not working
I was recently following the Firebase tutorial series by The Net Ninja YouTube channel.
The Net Ninja Firebase Function Playlist
Firebase Functions Tutorial #5 - Callable Functions
And I got stuck in the firebase functions part, first I was not even able to deploy them because billing was enabled in my account, then I put the node version in the package.json to '8', it didn't ask for billing when I deployed the functions.
package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
earlier it was
"node": "10"
After this, I'm able to deploy the functions and even run an onRequest function, but not the onCall function.
Whenever I try to call an onCall function, I don't know what happens, maybe I get an error I'm not sure.
index.js firebase function file
const functions = require('firebase-functions');
exports.randomNumber = functions.https.onRequest((request, response) => {
const number = Math.round(Math.random() * 100);
console.log(number);
response.send(number.toString());
});
exports.sayHello = functions.https.onCall((data, context) => {
console.log('its running');
return 'hello, ninjas';
});
The randomNumber runs perfectly, but sayHello never runs or whatever.
I'm calling the sayHello function from frontend
app.js my web app's javascript file
//sayHello function call
const button = document.querySelector('.call');
button.addEventListener('click', () => {
//get firebase function reference
const sayHello = firebase.functions().httpsCallable('sayHello');
sayHello().then(result => {
console.log(result.data);
}).catch(error => {
console.log(error);
});
});
I'm also initializing firebase properly in the index.html
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="/__/firebase/7.21.1/firebase-app.js"></script>
<!-- include only the Firebase features as you need -->
<script src="/__/firebase/7.21.1/firebase-auth.js"></script>
<script src="/__/firebase/7.21.1/firebase-firestore.js"></script>
<script src="/__/firebase/7.21.1/firebase-functions.js"></script>
<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>
In the console of my web app, something gets logged
Error: internal
at new y (error.ts:66)
at w (error.ts:175)
at A.<anonymous> (service.ts:245)
at tslib.es6.js:100
at Object.next (tslib.es6.js:81)
at r (tslib.es6.js:71)
Can anyone at least tell what this console log means???
Please help, not able to complete the tutorial series after which I'll move on to some real projects, been stuck at this for a week now.
Thanks in advance, if can solve my problem.
Solution found
Just downgrade the javascript sdk version you are using in your front end to 7.21.0, that's it, it'll work.
The issue was as stated by #DougStevenson below that Firebase callable functions, at the current time (Oct 2020) is not working with javascript sdk 7.21.1 and 7.22.0.
Cannot invoke HttpsCallable functions anymore after upgrading to firebase 7.22.0
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="/__/firebase/7.21.0/firebase-app.js"></script>
<!-- include only the Firebase features as you need -->
<script src="/__/firebase/7.21.0/firebase-auth.js"></script>
<script src="/__/firebase/7.21.0/firebase-firestore.js"></script>
<script src="/__/firebase/7.21.0/firebase-functions.js"></script>
<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>
I have found that callable functions from javascript web clients are broken with SDK version 7.21.1. If you downgrade to 7.21.0, it should work OK. The latest 7.22.0 still seems broken.
This has been filed on GitHub if you want to track it.
Update Oct 5, 2020: Apparently this has been fixed in 7.22.1.
Related
I want to test an app that only has Google Oauth Login via AWS Cognito. Lots of guides on how to use cypress to programatically login to Cognito using AWS Amplify with a username and password, but cannot find anything on how to do it with Google Oauth.
Im trying to use cypress to click the buttons to authenticate but I think there is a click forgery protection on Google.
I have also been able to use this cypress documentation to login to Google directly and get a jwt into session storage but not sure if there is a way to pass this to Cognito.
If you're doing end to end testing, then the simplest way would be to have another non prod staging environment without the Google Oauth login in Cognito, and instead the username password login you mentioned that has working examples.
This is also a good idea, as you shouldn't be using your production user system in testing anyway.
I tried many approaches to this including getting oauth token from Google and trying to exchange that manually with Cognito for the token I needed for AWS API Gateway. I also tried cypress-social-logins without success (because of this bug)
Finally I just wrote my own cypress steps to log me into my app with a valid session. NOTE THIS WILL NOT WORK IN A CI/CD because it will probably trigger Google validations and so it is a semi-automated solution.
If in doubt I recommend Tom Roman's answer below about creating a pre-prod environment in cognito that allows username/password login instead of messing about with google login.
// /support/login.js
Cypress.Commands.add('loginByGoogle', () => {
cy.visit('http://localhost:3030')
cy.origin('https://somecognitouserpool.auth.eu-west-1.amazoncognito.com', () => {
cy.contains('button', 'Continue with Google')
.click({force: true})
})
cy.origin('https://accounts.google.com', () => {
const resizeObserverLoopError = /^[^(ResizeObserver loop limit exceeded)]/;
Cypress.on('uncaught:exception', (err) => {
/* returning false here prevents Cypress from failing the test */
if (resizeObserverLoopError.test(err.message)) {
return false;
}
});
cy.get('input#identifierId[type="email"]')
.type(Cypress.env('googleSocialLoginUsername'))
.get('button[type="button"]').contains('Next')
.click()
.get('div#password input[type="password"]')
.type(Cypress.env('googleSocialLoginPassword'))
.get('button[type="button"]').contains('Next')
.click();
});
});
// /e2e/sometest.cy.js
before(() => {
cy.loginByGoogle();
});
describe('E2E testing', () => {
it('should now have a session', () => {
})
});
You also need a .env file (because you don't want to be saving your google credentials into github)
GOOGLE_USERNAME = ''
GOOGLE_PASSWORD = ''
You also need two experimental flags (as of 14th Nov 2022)
// cypress.config.js
const { defineConfig } = require('cypress');
require('dotenv').config()
module.exports = defineConfig({
env: {
googleSocialLoginUsername: process.env.GOOGLE_USERNAME,
googleSocialLoginPassword: process.env.GOOGLE_PASSWORD
},
e2e: {
experimentalSessionAndOrigin: true,
experimentalModifyObstructiveThirdPartyCode: true
}
})
Here is my package.json so that you can see the exact packages I am using.
In particular I added the flags --headed --no-exit in order to complete 2 factor authentication manually as necessary. I have not yet figured out how to stop Google asking for this every time.
{
"name": "docs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "http-server . -p 3030",
"cy:run": "cypress run --headed --no-exit",
"test": "start-server-and-test start http://localhost:3030 cy:run"
},
"author": "",
"license": "ISC",
"devDependencies": {
"cypress": "^11.0.1",
"start-server-and-test": "^1.14.0"
},
"dependencies": {
"dot-env": "^0.0.1",
"dotenv": "^16.0.3"
}
}
Im having an annoying problem which i've spent most of my day trying to solve without any luck - Also tried searching for a solution here and on Google, but without any luck, or at least all solution tried out didn't work.
When running my function, the firebase function log is telling me:
Cannot find module 'mailgun.js'
I have no idea why it won't resolve the module as it exist in the package.json file.
From the package.json:
"dependencies": {
"cors": "^2.8.5",
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1",
"form-data": "^4.0.0",
"mailgun.js": "^4.1.4"
},
I've have done a npm install inside the functions folder, and it deploys without problems, so the problem is when calling the function...
The code is:
import * as functions from "firebase-functions";
import Mailgun from "mailgun.js";
// eslint-disable-next-line #typescript-eslint/no-var-requires
const formData = require("form-data");
const domain = "https://app.mailgun.com/app/sending/domains/sandboxae7cd087b3854d25a6933f1fe489b5e3.mailgun.org";
const mgClient = new Mailgun(formData);
const mg = mgClient.client({
key: "mykey",
username: "api",
public_key: "mypublickey",
});
export const sendWelcomeEmailToClient = functions.https.onCall(
async (email: string) => {
return mg.messages.create(domain, {
from: "Task System",
to: email,
subject: "Testing",
html: "Dette er en test",
});
}
);
Please note, i've also tried doing a require instead of import on mailgun.js like so, but didn't work either:
Also, the mailgun documentation says that is the way to import it: https://www.npmjs.com/package/mailgun.js
const Mailgun = require("mailgun.js");
Solved it by using SendGrid instead of MailGun, that works as a charm...
I was reading this Reddit thread where a user mentioned that 540s is the limit of Firebase Functions and that moving to Cloud Run was recommended.
As others have said 540s is the maximum timeout and if you want to increase it without changing much else about your code, consider moving to Cloud Run. - #samtstern on Reddit
After looking at the Node.JS QuickStart documentation
and other content on YouTube and Google, I did not find a good guide explaining how to move your Firebase Function to Cloud Run.
One of the issues that were not addressed by what I read, for example: what do I replace the firebase-functions package with to define the function? Etc...
So, how may I move my Firebase Function over to Cloud Run to not run into the 540s max timeout limitation ?
const functions = require('firebase-functions');
const runtimeOpts = {timeoutSeconds: 540,memory: '2GB'}
exports.hourlyData = functions.runWith(runtimeOpts).pubsub.schedule('every 1 hours')
Preface: The following steps have been generalized for a wider audience than just the OP's problem (covers HTTP Event, Scheduled and Pub/Sub Functions) and have been adapted from the documentation linked in the question: Deploying Node.JS Images on Cloud Run.
Step 0: Code/Architecture Review
More often than not, exceeding the 9-minute timeout of a Cloud Function is a result of a bug in your code - make sure to evaluate this before switching to Cloud Run as this will just make the problem worse. The most common of these is sequential instead of parallelized asynchronous processing (normally caused by using await in a for/while loop).
If your code is doing meaningful work that is taking a long time, consider sharding it out to "subfunctions" that can all work on the input data in parallel. Instead of processing data for every user in your database, you can use a single function to trigger multiple instances of a function that each that take care of different user ID ranges such as a-l\uf8ff, m-z\uf8ff, A-L\uf8ff, M-Z\uf8ff and 0-9\uf8ff.
Lastly, Cloud Run and Cloud Functions are quite similar, they are designed to take a request, process it and then return a response. Cloud Functions have a limit of up to 9 minutes and Cloud Runs have a limit of up to 60 minutes. Once that response has been completed (because the server ended the response, the client lost connection or the client aborted the request), the instance is severely throttled or terminated. While you can use WebSockets and gRPC for a persistent communication between server and client when using Cloud Run, they are still subject to this limitation. See the Cloud Run: General development tips documentation for more information.
Like other serverless solutions, your client and server need to be able to handle connecting to different instances. Your code shouldn't make use of local state (like a local store for session data). See the Setting request timeout documentation for more information.
Step 1: Install Google Cloud SDK
I'll refer you to the Installing Google Cloud SDK documentation for this step.
Once installed, call gcloud auth login and login with the account used for the target Firebase project.
Step 2: Get your Firebase Project settings
Open up your project settings in the Firebase Console and take note of your Project ID and your Default GCP resource location.
Firebase Functions and Cloud Run instances should be co-located with your GCP resources where possible. In Firebase Functions, this is achieved by changing the region in code and deploying using the CLI. For Cloud Run, you specify these parameters on the command line as flags (or use the Google Cloud Console). For the below instructions and for simplicity, I will be using us-central1 as my Default GCP resources location is nam5 (us-central).
If using the Firebase Realtime Database in your project, visit your RTDB settings in the Firebase Console and take note of your Database URL. This is usually of the form https://PROJECT_ID.firebaseio.com/.
If using Firebase Storage in your project, visit your Cloud Storage settings in the Firebase Console and take note of your Bucket URI. From this URI, we need to take note of the host (ignore the gs:// part) which is usually of the form PROJECT_ID.appspot.com.
Here's a table that you can copy to help keep track:
Project ID:
PROJECT_ID
Database URL:
https://PROJECT_ID.firebaseio.com
Storage Bucket:
PROJECT_ID.appspot.com
Default GCP Resource Location:
Chosen Cloud Run Region:
Step 3: Create Directories
In your Firebase Project directory or a directory of your choosing, create a new cloudrun folder.
Unlike Firebase Cloud Functions, where you can define multiple functions in a single module of code, each Cloud Run image uses its own module of code. For this reason, each Cloud Run image should be stored in its own directory.
As we are going to define a Cloud Run instance called helloworld, we'll create a directory called helloworld inside cloudrun.
mkdir cloudrun
mkdir cloudrun/helloworld
cd cloudrun/helloworld
Step 4: Create package.json
For correct deployment of the Cloud Run image, we need to provide a package.json that is used to install dependencies in the deployed container.
The format of the package.json file resembles:
{
"name": "SERVICE_NAME",
"description": "",
"version": "1.0.0",
"private": true,
"main": "index.js",
"scripts": {
"start": "node index.js"
"image": "gcloud builds submit --tag gcr.io/PROJECT_ID/SERVICE_NAME --project PROJECT_ID",
"deploy:public": "gcloud run deploy SERVICE_NAME --image gcr.io/PROJECT_ID/SERVICE_NAME --allow-unauthenticated --region REGION_ID --project PROJECT_ID",
"deploy:private": "gcloud run deploy SERVICE_NAME --image gcr.io/PROJECT_ID/SERVICE_NAME --no-allow-unauthenticated --region REGION_ID --project PROJECT_ID",
"describe": "gcloud run services describe SERVICE_NAME --region REGION_ID --project PROJECT_ID --platform managed",
"find": "gcloud run services describe SERVICE_NAME --region REGION_ID --project PROJECT_ID --platform managed --format='value(status.url)'"
},
"engines": {
"node": ">= 12.0.0"
},
"author": "You",
"license": "Apache-2.0",
"dependencies": {
"express": "^4.17.1",
"body-parser": "^1.19.0",
/* ... */
},
"devDependencies": {
/* ... */
}
}
In the above file, SERVICE_NAME, REGION_ID and PROJECT_ID are to be swapped out as appropriate with the details from step 2. We also install express and body-parser to handle the incoming request.
There are also a handful of module scripts to help with deployment.
Script Name
Description
image
Submits the image to Cloud Build to be added to the Container Registry for other commands.
deploy:public
Deploys the image from the above command to be used by Cloud Run (while allowing any requester to invoke it) and returns its service URL (which is partly randomized).
deploy:private
Deploys the image from the above command to be used by Cloud Run (while requiring that the requester that invokes it is an authorized user/service account) and returns its service URL (which is partly randomized).
describe
Gets the statistics & configuration of the deployed Cloud Run.
find
Extracts only the service URL from the response of npm run describe
Note: Here, "Authorized User" refers to a Google Account associated with the project, not an ordinary Firebase User. To allow a Firebase User to invoke your Cloud Run, you must deploy it using deploy:public and handle token validation in your Cloud Run's code, rejecting requests appropriately.
As an example of this file filled in, you get this:
{
"name": "helloworld",
"description": "Simple hello world sample in Node with Firebase",
"version": "1.0.0",
"private": true,
"main": "index.js",
"scripts": {
"start": "node index.js"
"image": "gcloud builds submit --tag gcr.io/com-example-cloudrun/helloworld --project com-example-cloudrun",
"deploy:public": "gcloud run deploy helloworld --image gcr.io/com-example-cloudrun/helloworld --allow-unauthenticated --region us-central1 --project com-example-cloudrun",
"deploy:public": "gcloud run deploy helloworld --image gcr.io/com-example-cloudrun/helloworld --no-allow-unauthenticated --region us-central1 --project com-example-cloudrun",
"describe": "gcloud run services describe helloworld --region us-central1 --project com-example-cloudrun --platform managed",
"find": "gcloud run services describe helloworld --region us-central1 --project com-example-cloudrun --platform managed --format='value(status.url)'"
},
"engines": {
"node": ">= 12.0.0"
},
"author": "You",
"license": "Apache-2.0",
"dependencies": {
/* ... */
},
"devDependencies": {
/* ... */
}
}
Step 5: Create your container files
To tell Cloud Build what container to use for your Cloud Run image, you must create a Dockerfile for your image. To prevent sending the wrong files to the server, you should also specify a .dockerignore file.
In this file, we use the Firebase Project settings from Step 2 to recreate the process.env.FIREBASE_CONFIG environment variable. This variable is used by the Firebase Admin SDK and contains the following information as a JSON string:
{
databaseURL: "https://PROJECT_ID.firebaseio.com",
storageBucket: "PROJECT_ID.appspot.com",
projectId: "PROJECT_ID"
}
Here is cloudrun/helloworld/Dockerfile:
# Use the official lightweight Node.js 14 image.
# https://hub.docker.com/_/node
FROM node:14-slim
# Create and change to the app directory.
WORKDIR /usr/src/app
# Copy application dependency manifests to the container image.
# A wildcard is used to ensure copying both package.json AND package-lock.json (when available).
# Copying this first prevents re-running npm install on every code change.
COPY package*.json ./
# Install production dependencies.
# If you add a package-lock.json, speed your build by switching to 'npm ci'.
# RUN npm ci --only=production
RUN npm install --only=production
# Copy local code to the container image.
COPY . ./
# Define default configuration for Admin SDK
# databaseURL is usually "https://PROJECT_ID.firebaseio.com", but may be different.
# TODO: Update me
ENV FIREBASE_CONFIG={"databaseURL":"https://PROJECT_ID.firebaseio.com","storageBucket":"PROJECT_ID.appspot.com","projectId":"PROJECT_ID"}
# Run the web service on container startup.
CMD [ "node", "index.js" ]
Here is cloudrun/helloworld/.dockerignore:
Dockerfile
.dockerignore
node_modules
npm-debug.log
Step 6: Create & deploy your entry point
When a new Cloud Run instance is launched, it will normally specify the port it wants your code to listen on using the PORT environment variable.
Variant: Migrating a HTTP Event Function
When you use a HTTP Event function from the firebase-functions package, it internally handles body-parsing on your behalf. The Functions Framework uses the body-parser package for this and defines the parsers here.
To handle user authorization, you could use this validateFirebaseIdToken() middleware to check the ID token given with the request.
For a HTTP-based Cloud Run, configuring CORS will be required to invoke it from a browser. This can be done by installing the cors package and configuring it appropriately. In the below sample, cors will reflect the origin sent to it.
const express = require('express');
const cors = require('cors')({origin: true});
const app = express();
app.use(cors);
// To replicate a Cloud Function's body parsing, refer to
// https://github.com/GoogleCloudPlatform/functions-framework-nodejs/blob/d894b490dda7c5fd4690cac884fd9e41a08b6668/src/server.ts#L47-L95
// app.use(/* body parsers */);
app.enable('trust proxy'); // To respect X-Forwarded-For header. (Cloud Run is behind a load balancer proxy)
app.disable('x-powered-by'); // Disables the 'x-powered-by' header added by express (best practice)
// Start of your handlers
app.get('/', (req, res) => {
const name = process.env.NAME || 'World';
res.send(`Hello ${name}!`);
});
// End of your handlers
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`helloworld: listening on port ${port}`);
});
In the $FIREBASE_PROJECT_DIR/cloudrun/helloworld directory, execute the following commands to deploy your image:
npm run image // builds container & stores to container repository
npm run deploy:public // deploys container image to Cloud Run
Variant: Invoke using Cloud Scheduler
When invoking a Cloud Run using the Cloud Scheduler, you can choose which method is used to invoke it (GET, POST (the default), PUT, HEAD, DELETE). To replicate a Cloud Function's data and context parameters, it is best to use POST as these will then be passed in the body of the request. Like Firebase Functions, these requests from Cloud Scheduler may be retried so make sure to handle idempotency appropriately.
Note: Even though the body of a Cloud Scheduler invocation request is JSON-formatted, the request is served with Content-Type: text/plain, which we need to handle.
This code has been adapted from the Functions Framework source (Google LLC, Apache 2.0)
const express = require('express');
const { json } = require('body-parser');
async function handler(data, context) {
/* your logic here */
const name = process.env.NAME || 'World';
console.log(`Hello ${name}!`);
}
const app = express();
// Cloud Scheduler requests contain JSON using
"Content-Type: text/plain"
app.use(json({ type: '*/*' }));
app.enable('trust proxy'); // To respect X-Forwarded-For header. (Cloud Run is behind a load balancer proxy)
app.disable('x-powered-by'); // Disables the 'x-powered-by' header added by express (best practice)
app.post('/*', (req, res) => {
const event = req.body;
let data = event.data;
let context = event.context;
if (context === undefined) {
// Support legacy events and CloudEvents in structured content mode, with
// context properties represented as event top-level properties.
// Context is everything but data.
context = event;
// Clear the property before removing field so the data object
// is not deleted.
context.data = undefined;
delete context.data;
}
Promise.resolve()
.then(() => handler(data, context))
.then(
() => {
// finished without error
// the return value of `handler` is ignored because
// this isn't a callable function
res.sendStatus(204); // No content
},
(err) => {
// handler threw error
console.error(err.stack);
res.set('X-Google-Status', 'error');
// Send back the error's message (as calls to this endpoint
// are authenticated project users/service accounts)
res.send(err.message);
}
)
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`helloworld: listening on port ${port}`);
});
Note: The Functions Framework handles errors by sending back a HTTP 200 OK response with a X-Google-Status: error header. This effectively means "failed successfully". As an outsider, I'm not sure why this is done but I can assume it's so that the invoker knows to not bother retrying the function - it'll just get the same result.
In the $FIREBASE_PROJECT_DIR/cloudrun/helloworld directory, execute the following commands to deploy your image:
npm run image // builds container & stores to container repository
npm run deploy:private // deploys container image to Cloud Run
Note: In the following setup commands (only need to run these once), PROJECT_ID, SERVICE_NAME, SERVICE_URL and IAM_ACCOUNT will need to be substituted as appropriate.
Next we need to create a service account that Cloud Scheduler can use to invoke the Cloud Run. You can call it whatever you want such as scheduled-run-invoker. The email of this service account will be referred to as IAM_ACCOUNT in the next step. This Google Cloud Tech YouTube video (starts at the right spot, about 15s) will quickly show what you need to do. Once you've created the account, you can create the Cloud Scheduler job following the next 30 or so seconds of the video or use the following command:
gcloud scheduler jobs create http scheduled-run-SERVICE_NAME /
--schedule="every 1 hours" /
--uri SERVICE_URL /
--attempt-deadline 60m /
--http-method post /
--message-body='{"optional-custom-data":"here","if-you":"want"}' /
--oidc-service-account-email IAM_ACCOUNT
--project PROJECT_ID
Your Cloud Run should now be scheduled.
Variant: Invoke using Pub/Sub
To my understanding, the deploy process is the same as for a scheduled run (deploy:private) but I'm unsure about the specifics. However, here is the Cloud Run source for a Pub/Sub parser:
This code has been adapted from the Functions Framework source (Google LLC, Apache 2.0)
const express = require('express');
const { json } = require('body-parser');
const PUBSUB_EVENT_TYPE = 'google.pubsub.topic.publish';
const PUBSUB_MESSAGE_TYPE =
'type.googleapis.com/google.pubsub.v1.PubsubMessage';
const PUBSUB_SERVICE = 'pubsub.googleapis.com';
/**
* Extract the Pub/Sub topic name from the HTTP request path.
* #param path the URL path of the http request
* #returns the Pub/Sub topic name if the path matches the expected format,
* null otherwise
*/
const extractPubSubTopic = (path: string): string | null => {
const parsedTopic = path.match(/projects\/[^/?]+\/topics\/[^/?]+/);
if (parsedTopic) {
return parsedTopic[0];
}
console.warn('Failed to extract the topic name from the URL path.');
console.warn(
"Configure your subscription's push endpoint to use the following path: ",
'projects/PROJECT_NAME/topics/TOPIC_NAME'
);
return null;
};
async function handler(message, context) {
/* your logic here */
const name = message.json.name || message.json || 'World';
console.log(`Hello ${name}!`);
}
const app = express();
// Cloud Scheduler requests contain JSON using
"Content-Type: text/plain"
app.use(json({ type: '*/*' }));
app.enable('trust proxy'); // To respect X-Forwarded-For header. (Cloud Run is behind a load balancer proxy)
app.disable('x-powered-by'); // Disables the 'x-powered-by' header added by express (best practice)
app.post('/*', (req, res) => {
const body = req.body;
if (!body) {
res.status(400).send('no Pub/Sub message received');
return;
}
if (typeof body !== "object" || body.message === undefined) {
res.status(400).send('invalid Pub/Sub message format');
return;
}
const context = {
eventId: body.message.messageId,
timestamp: body.message.publishTime || new Date().toISOString(),
eventType: PUBSUB_EVENT_TYPE,
resource: {
service: PUBSUB_SERVICE,
type: PUBSUB_MESSAGE_TYPE,
name: extractPubSubTopic(req.path),
},
};
// for storing parsed form of body.message.data
let _jsonData = undefined;
const data = {
'#type': PUBSUB_MESSAGE_TYPE,
data: body.message.data,
attributes: body.message.attributes || {},
get json() {
if (_jsonData === undefined) {
const decodedString = Buffer.from(base64encoded, 'base64')
.toString('utf8');
try {
_jsonData = JSON.parse(decodedString);
} catch (parseError) {
// fallback to raw string
_jsonData = decodedString;
}
}
return _jsonData;
}
};
Promise.resolve()
.then(() => handler(data, context))
.then(
() => {
// finished without error
// the return value of `handler` is ignored because
// this isn't a callable function
res.sendStatus(204); // No content
},
(err) => {
// handler threw error
console.error(err.stack);
res.set('X-Google-Status', 'error');
// Send back the error's message (as calls to this endpoint
// are authenticated project users/service accounts)
res.send(err.message);
}
)
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`helloworld: listening on port ${port}`);
});
I have decided to use firebase as a backend for authentication and basic form information with firestore.
In the past I've used this express api in cloud functions to do this, and am basing this new setup off of that. But I'm looking to just use it on a Vultr Centos server instead, to put with the rest of my api, and just make everything easier for now as i don't want to overcomplicate things (until later :P).
Now - I've just cloned this repo onto my server, and I want to test it with postman, and i'm having trouble just accessing it.
I'm not sure how to solve the issue and if anyone could point me in the right direction that would make my life so much easier!
here is the index file and the package json file currently. I've created the server.listen to try and make it work at the moment.
const functions = require("firebase-functions");
const app = require("express")();
const FBAuth = require("./util/fbAuth");
const server = require('http').createServer(app);
const cors = require("cors");
//This was recently added to try and make it all work easier!
server.listen(port, ipaddress, () => {
});
app.use(cors());
const { db } = require("./util/admin");
const {
getAllWorkflows,
...
} = require("./handlers/workflow");
const {
signup,
login,
uploadImage,
addUserDetails,
getAuthenticatedUser,
getUserDetails
} = require("./handlers/users");
// Workflow Routes
app.get("/Workflows", getAllWorkflows);
...
// user route
app.post("/user", FBAuth, addUserDetails);
app.post("/user/image", FBAuth, uploadImage);
...
// cloud functions are better than firebase library because of load time.
exports.api = functions.https.onRequest(app);
here is the package.json file.
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"dependencies": {
"busboy": "^0.3.1",
"cors": "^2.8.5",
"express": "^4.17.1",
"firebase": "^7.21.1",
"firebase-admin": "^8.9.0",
"firebase-functions": "^3.11.0",
"firebase-tools": "^7.11.0"
},
"devDependencies": {
"firebase-functions-test": "^0.1.6",
"node-gyp": "^5.0.7"
},
"private": true
}
With the backend i am fixing up, I use this sort of workthrough (if it helps!), which I am replacing with firebase stuff above - if that makes sense. It works currently, is accessible for signup and login functionality, the key part for me is just using firebase and firestore with it.
const config = require('../../config');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
.....
server.listen(config.serverParams.port, config.serverParams.address, () => {
console.log(`Server running at http://${server.address().address}:${server.address().port}`);
});
....
app.use((req,res,next)=>{
//can reaplce * with website we want to allow access
res.header('Access-Control-Allow-Origin', 'https://moodmap.app/stats');
next();
});
....
io.on('connection', socket => {
socket.use((packet, next) => {
.....
});
});
Really appreciate any guidance on this matter!
Firebase and firestore seems like a nice way to avoid reinventing the wheel, if only i could simply type npm start, and begin testing with postman the underlying functionality :s
The API is based off another side project i did, which is largely here for those interested in exploring it more.
https://github.com/Hewlbern/LightSpeed/tree/master/sigops
Very happy to just use the easiest way forward - I don't want to have any of the libraries on the client side though, as i want to make my front end super efficient. Thanks!
Cloud Functions does not allow you to listen on any ports in order to receive requests. It automatically handles incoming connections using the URL automatically provided during deployment. All incoming requests to that URL are routed to your function callback defined by the exported function built by functions.https.onRequest().
If you require the ability to listen to specific ports, Cloud Functions is not the right product for your use case. Cloud Functions can not be deployed on custom servers - it only works on infrastructure provided by Google.
I am trying to add email to a firebase cloud function. However, when ever I add the line:
const nodemailer = require('nodemailer');
to index.js, code which previously deployed will no longer deploy. It reports that one of my functions had an error, but this can't be the case cause it works just fine with that function. Here is the full code, runs without the line just fine.
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
admin.initializeApp();
exports.routineKick = functions.pubsub
.schedule('every 2 minutes')
.timeZone('America/New_York')
.onRun(context => {
//kickMembers();
}
);
Posting the solution as a Community Wiki since this solution was shared by an edit to the question itself by the OP.
The problem is that the app was missing the nodemailer dependency. It can be fixed by doing the following:
In the package.JSON file, located at the functions folder, add under dependencies the following: "nodemailer": "^6.4.3" or whatever version you have.
I'm using node mailer version of 6.7.0, In the "package.JSON" file, downgrade node version from 14 to 10 works for me
"engines": {
"node": "10"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1",
"nodemailer": "^6.7.0"
},