firebase emulator cannot refresh dynamic import Functions - firebase

Background
I use dynamic import for Firebase Functions to reduce cold start time based on this post: https://medium.com/firebase-developers/organize-cloud-functions-for-max-cold-start-performance-and-readability-with-typescript-and-9261ee8450f0
index.ts under functions folder has only one line
exports.consent = require("./myFunctionGroup");
index.ts under functions/myFunctionGroup
import * as functions from "firebase-functions";
export const helloWorld = functions.https.onCall(async (data, context) => {
return await (await import("./helloWorld")).default(data, context);
});
Content of helloWorld.ts under functions/myFunctionGroup
import * as functions from "firebase-functions";
export default async (
data: {},
context: functions.https.CallableContext
) => {
return "hello";
}
There is no problem when the emulator first launched as it return "hello" correctly. However, when I change to return to 'return "world";', even though the emulator seems to be aware of the change and prints ✔ functions: Loaded functions definitions from source:..., it still return the old value of hello. Maybe it has some kind of cache for the original imported module. When I restart process again, then it will then print "world".
Question:
Is there any setting to make the emulator aware my change and force to clear the Functions cache? I tried to use debugger and it realized my code has changed so that I can step through the new code. It's just not working for the Firebase emulator.

It was expected behavior,any changes/modification in the code after running the emulator will not be reflected. You can also refer to this documentation:
Note:Code changes you make during an active session are automatically
reloaded by the emulator. If your code needs to be transpiled
(TypeScript, React) make sure to do so before running the emulator.
You can run your transpiler in watch mode with commands like tsc -w to
transpile and reload code automatically as you save.
You can follow the below steps,As mentioned in this stackoverflow thread
After every change to the ts files, run "npm run build" to compile the code again.
Change "build": "tsc" to "build": "tsc -w" in package.json if you want to auto-compile after every change.
There is a bug raised for this at github which is still open you can track the updates there.

Related

How to implement Firebase AppCheck inside firebase function to read Realtime database? [duplicate]

I recently enabled App Check for my firebase app and enforced it on both my cloud functions and database. The cloud function workflow is behaving correctly. However, I can no longer access the database from the function. A minimal version of my callable function looks something like this:
exports.myFunc = functions.https.onCall(async (data, context) => {
const adminApp = admin.initializeApp();
const ref = adminApp.database().ref('some-node');
if (context.app === undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.',
);
}
try {
return (await ref.orderByKey().equalTo('foo').get()).exists()
} catch(exc) {
console.error(exc);
}
});
This used to work before App Check, but now it fails and I see this in the logs:
#firebase/database: FIREBASE WARNING: Invalid appcheck token (https://my-project-default-rtdb.firebaseio.com/)
Error: Error: Client is offline.
Seems like I need to do something extra to get the admin app to pass App Check verification down to the database, but I haven't been able to find any documentation on this yet. I also tried using the app instance from functions.app.admin instead of initializing a new one, but this didn't help.
I have the latest version of the packages:
"firebase-admin": "^9.10.0"
"firebase-functions": "^3.14.1"
firebaser here
The behavior you're seeing is not how it's supposed to work, and we've been able to reproduce it. Thanks for the clear report, and sorry you encountered this.
If you (re)install the Firebase Admin SDK today, you won't be experiencing this same problem as we've fixed the problem in the #firebase/database dependency (in this PR).
If you're (still) experiencing the problem, you can check if you have the correct #firebase/database dependency by running:
npm ls #firebase/database
results look something like this:
temp-admin#1.0.0 /Users/you/repos/temp-admin
└─┬ firebase-admin#9.11.0
└── #firebase/database#0.10.8
If your #firebase/database version is lower than 0.10.8, you'll have to reinstall the Admin SDK, for example by deleting your node_modules directory and your package-lock.json file and running npm install again. This may also update other dependencies.

Firebase App Check not working with firebase functions - web project [duplicate]

I recently enabled App Check for my firebase app and enforced it on both my cloud functions and database. The cloud function workflow is behaving correctly. However, I can no longer access the database from the function. A minimal version of my callable function looks something like this:
exports.myFunc = functions.https.onCall(async (data, context) => {
const adminApp = admin.initializeApp();
const ref = adminApp.database().ref('some-node');
if (context.app === undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.',
);
}
try {
return (await ref.orderByKey().equalTo('foo').get()).exists()
} catch(exc) {
console.error(exc);
}
});
This used to work before App Check, but now it fails and I see this in the logs:
#firebase/database: FIREBASE WARNING: Invalid appcheck token (https://my-project-default-rtdb.firebaseio.com/)
Error: Error: Client is offline.
Seems like I need to do something extra to get the admin app to pass App Check verification down to the database, but I haven't been able to find any documentation on this yet. I also tried using the app instance from functions.app.admin instead of initializing a new one, but this didn't help.
I have the latest version of the packages:
"firebase-admin": "^9.10.0"
"firebase-functions": "^3.14.1"
firebaser here
The behavior you're seeing is not how it's supposed to work, and we've been able to reproduce it. Thanks for the clear report, and sorry you encountered this.
If you (re)install the Firebase Admin SDK today, you won't be experiencing this same problem as we've fixed the problem in the #firebase/database dependency (in this PR).
If you're (still) experiencing the problem, you can check if you have the correct #firebase/database dependency by running:
npm ls #firebase/database
results look something like this:
temp-admin#1.0.0 /Users/you/repos/temp-admin
└─┬ firebase-admin#9.11.0
└── #firebase/database#0.10.8
If your #firebase/database version is lower than 0.10.8, you'll have to reinstall the Admin SDK, for example by deleting your node_modules directory and your package-lock.json file and running npm install again. This may also update other dependencies.

Next.js - Is it possible to debug getServerSideProps?

Hi as per docs getServerSideProps is a function which is executed only on server side.
export async function getServerSideProps(context) {
console.log("hello world");
debugger;
return {
props: {
age:55
}, // will be passed to the page component as props
}
}
As a consequence simply dropping a debugger keyword won't work.
I have tried:
Attaching the node.js debugger on port 9229
Running node --inspect-brk ./node_modules/next/dist/bin/next
Running cross-env NODE_OPTIONS='--inspect' next dev
But neither console.log() nor debugger keyword seem to have any effect.
However my props from getServerSideProps are passed in correctly, which proves the function is called.
Is it possible to stepthrough getServerSideProps or at least get console.log working? Thanks!
P.S.
The lines of code outside getServerSideProps are debuggable and work as expected.
In order to make the open the debug port open properly, you need to do the following:
// package.json scripts
"dev": "NODE_OPTIONS='--inspect' next dev"
// if you want custom debug port on a custom server
"dev": "NODE_OPTIONS='--inspect=5009' node server.js",
Once the debug port is own, you should be able to use inspector clients of your choice.
I had the same problem and I solved it with following steps. First, I installed cross-envpackage with
npm install cross-env
then I had to adjust my package.json with
"dev": "cross-env NODE_OPTIONS='--inspect' next dev",
After that you should be able to run npm run dev.
Open localhost:3000 or whatever port u are normally running nextjs app on. Open new tab and type
chrome://inspect
You should be able to see path to your app with word inspect at the end. After clicking new devTools will be opened with ability to set up breakpoints inside e.g. getStaticPaths, getStaticProps or getServerSideProps.

Firebase-tools is not uploading newly created functions to Firebase

I am working on an Angular project and I am writing Firebase functions that I would like to deploy to Firebase. As I write more functions for Firebase and try to deploy them to Firebase using firebase deploy --only functions, only existing functions get deployed. More specifically, I have 16 functions that I would like to deploy to Firebase but only the same 12 get deployed.
So far, I have done the following to try to fix the problem:
I made sure that I am on the latest firebase-tools (6.7.0)
I have tried specifying the newly written functions I would like to deploy using firebase deploy --only functions:<NEW FUNCTION NAME HERE>
Remove all export functions from the functions/src/index.ts file and upload a blank index.ts. Even when using a blank index.ts file, the same functions still get deployed to Firebase.
I know there can be up to a 30-second delay when uploading functions to Firebase, so I have even waited for an entire night before trying to upload new functions.
I have started from complete scratch using firebase init to recreate the whole functions directory and it still keeps uploading the same functions.
I upgraded from the free Firebase plan to the Spark plan.
The following code is the main index.ts file which is located in functions/src/index.ts.
import * as functions from 'firebase-functions';
import { firestore } from 'firebase-admin';
import * as moment from 'moment';
import { request } from 'https';
// Local Functions Imports
import * as Permissions from './permissions';
import * as Groups from './groups';
import * as Shifts from './shifts';
import * as Roles from './roles';
import * as Session from './sessions';
import * as Users from './users';
import * as Slack from './slack';
import * as ScheduleChanges from './schedule-changes';
import * as Email from './email';
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/* -------- USER MANAGEMENT -------------- */
export const createUser = Users.createUser;
export const addUserToDefaultJoinGroups = Users.addUserToDefaultJoinGroups;
export const deleteUser = Users.deleteUser;
/* -------- SESSION MANAGEMENT -------------- */
export const addSessionID = Session.addSessionID;
/* -------- ROLE MANAGEMENT -------------- */
export const addRoleID = Roles.addRoleID;
export const removeAllShiftsAssociatedWithRole = Roles.removeAllShiftsAssociatedWithRole;
/* -------- SHIFT MANAGEMENT -------------- */
export const addShiftID = Shifts.addShiftID;
export const hourly_job = Shifts.hourly_job;
export const changeShiftStatsTest = Shifts.changeShiftStatsTest;
/* -------- GROUPS MANAGEMENT -------------- */
export const addGroupID = Groups.addGroupID;
export const addGroupIDNewTestFunction = Groups.addGroupIDNewTestFunction;
/* -------- PERMISSIONS MANAGEMENT -------------- */
export const addPermissionID = Permissions.addPermissionID;
/* -------- Emailing -------------- */
export const sendWelcomeEmailToNewUser = Email.sendWelcomeEmailToNewUser;
export const sendWelcomeEmailToNewUser2 = Email.sendWelcomeEmailToNewUser2;
/* -------- SLACK MESSAGING MANAGEMENT -------------- */
export const sendWelcomingMessage = Slack.sendWelcomingMessage;
/* -------- SCHEDULE CHANGES MANAGEMENT -------------- */
export const addScheduleChangeID = ScheduleChanges.addScheduleChangeID;
As seen in the code above, there are 16 functions that should be deployed to Firebase. However, only 12 get deployed. The following code snippet is from functions/src/groups/index.ts. In this file, the addGroupID is an existing function which continually gets deployed to Firebase. On the other hand, addGroupIDNewTestFunction is a new function that isn't getting deployed to Firebase even though they are in the same file and being referenced the same way.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
export const addGroupID = functions.firestore
.document("organizations/{organizationID}/groups/{groupID}")
.onCreate(async (snap, context) => {
console.log("Adding group id");
await admin.firestore()
.doc(`organizations/${context.params.organizationID}/groups/${context.params.groupID}`).update({
'groupID': context.params.groupID
})
})
export const addGroupIDNewTestFunction = functions.firestore
.document("organizations/{organizationID}/groups2/{groupID}")
.onCreate(async (snap, context) => {
console.log("Adding group id");
await admin.firestore()
.doc(`organizations/${context.params.organizationID}/groups/${context.params.groupID}`).update({
'groupID': context.params.groupID
})
})
As mentioned previously, I have specified 16 functions in the main index.ts file that should get deployed to Firebase functions. However, only the existing 12 functions are getting deployed. The following code snippet is the output firebase gives me when I run firebase deploy --only functions inside the Angular project.
firebase deploy --only functions
=== Deploying to 'university-scheduling'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions
> tslint --project tsconfig.json
no-unused-variable is deprecated. Since TypeScript 2.9. Please use the built-in compiler checks instead.
Could not find implementations for the following rules specified in the configuration:
use-input-property-decorator
use-output-property-decorator
use-host-property-decorator
Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.
If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/email/index.ts:2:13 - 'admin' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:2:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:3:13 - 'moment' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:4:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:2:13 - 'admin' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:6:7 - 'request' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:7:7 - 'options' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:3:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:43:11 - 'groups' is declared but itsvalue is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:65:11 - 'uid' is declared but its value is never read.
Running command: npm --prefix "$RESOURCE_DIR" run build
> functions# build /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions
> tsc
✔ functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (106.24 KB) for uploading
✔ functions: functions folder uploaded successfully
⚠ appEngineLocation us-central1
i functions: updating Node.js 6 function createUser(us-central1)...
i functions: updating Node.js 6 function deleteUser(us-central1)...
i functions: updating Node.js 6 function addSessionID(us-central1)...
i functions: updating Node.js 6 function addRoleID(us-central1)...
i functions: updating Node.js 6 function removeAllShiftsAssociatedWithRole(us-central1)...
i functions: updating Node.js 6 function addShiftID(us-central1)...
i functions: updating Node.js 6 function hourly_job(us-central1)...
i functions: updating Node.js 6 function changeShiftStatsTest(us-central1)...
i functions: updating Node.js 6 function addGroupID(us-central1)...
i functions: updating Node.js 6 function addPermissionID(us-central1)...
i functions: updating Node.js 6 function sendWelcomingMessage(us-central1)...
i functions: updating Node.js 6 function addScheduleChangeID(us-central1)...
✔ scheduler: all necessary APIs are enabled
✔ functions[addPermissionID(us-central1)]: Successful update operation.
✔ functions[createUser(us-central1)]: Successful update operation.
✔ functions[addShiftID(us-central1)]: Successful update operation.
✔ functions[changeShiftStatsTest(us-central1)]: Successful update operation.
✔ functions[sendWelcomingMessage(us-central1)]: Successful update operation.
✔ functions[hourly_job(us-central1)]: Successful update operation.
✔ functions[addSessionID(us-central1)]: Successful update operation.
✔ functions[deleteUser(us-central1)]: Successful update operation.
✔ functions[addGroupID(us-central1)]: Successful update operation.
✔ functions[removeAllShiftsAssociatedWithRole(us-central1)]: Successful update operation.
✔ functions[addScheduleChangeID(us-central1)]: Successful update operation.
✔ functions[addRoleID(us-central1)]: Successful update operation.
✔ Deploy complete!
Please note that it can take up to 30 seconds for your updated functions to propagate.
You should check the directory which is compiled js files.
The default is functions/lib/.
If you import like ../../foo.ts anywhere at functions/src or functions/src/tests, etc then the compiled js file is functions/lib/{any}/foo.js.
The deploy target files are functions/lib/*.js only. So, functions/lib/{any}/foo.js is ignored.
You should change directory or files structure.
If the reason is test files then you should meke tsconfig.json for deploy and exclude them.
I wanted to give you guys an update on the solution to the problem I described above. In one of my index.ts files, I had the following require statement, var mailgun = require('mailgun-js'). Whenever I replaced this the require statement with import * as mailgun from 'mailgun-js', all the functions were deployed properly.
The most confusing part about this whole issue was that I only received success messages even when things weren't working properly. I do thank you guys for the speedy support and all of your suggestions!!
I had the exact same problem and the solution was Editing functions/src/index.ts instead of functions/lib/index.js
In my case it's index.ts because of I selected that option when initialized the project with "firebase init", your case depends on it, can be index.js too, but always on /src and not in /lib.
I think that the /lib folder if for the compiled file.
When deploying functions the compiler converts the src/.ts files into "lib/src/.js" files.
Somehow I had some files hanging around from previous deployments in the "lib/*js" space. Sure enough these files were getting deployed but the files containing the new function I had created were located in "lib/src/*js. No new changes were being passed up into cloud functions.
and so I went into package.json and changed
"main": "lib/index.js",
to read
"main": "lib/src/index.js",
And to cleanup I deleted all .js files from "lib/
I was back in business.

Deploying firebase cloud function in typescript

I'm trying to deploy the very first cloud function.
It works perfectly fine, but when I try to deploy it in terminal, it sets out warning saying that "functions is declared but it's value is never read".
Is this some common starting mistake, as I am new to this subject? Thank you.
I tried both imports , deploy erros remains same
// const functions = require('firebase-functions');
import * as functions from 'firebase-functions'
Errors message
index.ts file code here
Your code doesn't declare any Cloud Functions yet, so eslint warns you that you're importing functions but not using it.
The message will disappear when you declare a Cloud Function in your index.js/index.ts. For example, the documentation on getting started contains this example:
exports.addMessage = functions.https.onRequest((req, res) => {
const original = req.query.text;
return admin.database().ref('/messages').push({original: original}).then((snapshot) => {
return res.redirect(303, snapshot.ref.toString());
});
});
As you can see, this code uses functions in its first line. So if you add this (or any other Cloud Functions declaration) to your code, you're using functions and eslint will no longer warn you about it not being used.
The error will disappear when you finally use "functions" in a cloud function.
nevermind, you are better off using
const functions = require('firebase-functions');
when importing firebase-functions in your index.js
========
EDIT : ======
Make sure that you have correctly installed those dependencies, by running those npm commands in the right folder:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
Probably solved, but for me I was expecting ~/functions/index.ts to be the file building but the firebase cli added ~/functions/src/index.ts and THAT was the file.

Resources