My code: Inside of an index.js file. Set up using firebase init command, functions selected. I'm able to deploy without error if I comment out the code:
const firebase = require("firebase");
firebase.initializeApp(config);
It throws the error if I leave this in. I've tried running npm install and npm rebuild in both the functions folder and the parent folder.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const app = require("express")();
admin.initializeApp();
const config = {
apiKey: "apiKey",
authDomain: "socialapp.firebaseapp.com",
databaseURL: "https://socialapp.firebaseio.com"
storageBucket: "socialapp.appspot.com"
};
const firebase = require("firebase");
firebase.initializeApp(config);
app.get("/screams", (req, res) => {
admin
.firestore()
.collection("screams")
.orderBy("createdAt", "descending")
.get()
.then(data => {
let screams = [];
data.forEach(doc => {
screams.push({
screamId: doc.id,
body: doc.data().body,
userHandle: doc.data().userHandle,
createdAt: doc.data().createdAt
});
});
return res.json(screams);
})
.catch(err => console.log(err));
});
app.post("/scream", (req, res) => {
const newScream = {
body: req.body.body,
userHandle: req.body.userHandle,
createdAt: new Date().toISOString()
};
admin
.firestore()
.collection("screams")
.add(newScream)
.then(doc => {
res.json({ message: `document ${doc.id} created successfully` });
})
.catch(err => {
res.status(500).json({ error: "Something went wrong." });
console.error(err);
});
});
//Signup Route
app.post("/signup", (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle
};
//Todo validate data
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res
.status(201)
.json({ message: `user ${data.user.uid} signed up successfully` });
})
.catch(err => {
console.err(error);
return res.status(500).json({ error: err.code });
});
});
exports.api = functions.https.onRequest(app);
Error from console:
i deploying functions
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
Error: Error parsing triggers: The gRPC binary module was not installed. This may be fixed by running "npm rebuild"
Original error: Cannot find module 'C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\node\extension_binary\node-v79-win32-x64-unknown\grpc_node.node'
Require stack:
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\grpc_extension.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\client_interceptors.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\client.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\index.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\#firebase\firestore\dist\index.node.cjs.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\firebase\dist\index.node.cjs.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\index.js
- C:\Users\alex_\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js
Try running "npm install" in your functions directory before deploying.
Having trouble? Try firebase [command] --help
You don't need the "firebase" module here (it's mostly meant for web application, note nodejs apps). You can use the Admin SDK instead to create a user account as described in the documentation.
Related
I wanted to test a firestore rule. Below is firestore.rules. I wanted to check that these security rules are valid. Then I tried to use jest and firebase testing. However when executing "npm test", an error, "connect ECONNREFUSED 127.0.0.1:8080" occured.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /clubUsers/{uid} {
allow read: if request.auth != null
&& request.auth.uid == uid;
allow create: if request.auth != null
&& request.auth.uid == uid;
allow update: if request.auth != null
&& request.auth.uid == uid;
}
}
}
And my test script is here.
const firebase = require('#firebase/testing/');
const fs = require('fs');
const project_id = "PROJECT ID";
describe("testing firestore rules", () => {
beforeAll(
async () => {
await firebase.loadFirestoreRules({
projectId: project_id,
rules: fs.readFileSync('../../firestore.rules', 'utf8'),
});
}
);
afterEach(
async () => {
await firebase.clearFirestoreData({ projectId: project_id });
}
);
afterAll(
async () => {
await Promise.all(
firebase.apps().map((app) => app.delete())
);
}
);
function authedApp(auth) {
return firebase.initializeTestApp({
projectId: project_id,
auth: auth,
}).firestore();
}
describe("testing get and write", () => {
test("testing get", async () => {
const db = authedApp({ uid: 'UID' });
const message = db.collection("clubUsers").doc("UID");
await firebase.assertSucceeds(message.get());
})
test("testing write", async () => {
const db = authedApp({ uid: "UID" });
const message = db.collection("clubUsers").doc("UID");
await firebase.assertSucceeds(
message.set({ text: "hoge" })
);
})
})
})
I tried the test while firebase emulator is opened.
I checked what is using port 8080 by executing sudo lsof -P -i:8080 on terminal.
However, nothing has used port 8080.
Just ran into this too today... a couple of sources (GitHub and here) led to a solution. This is an issue with the call to firebase.clearFirestoreData() and occurs when the emulator can't be found on the default host:port it is expecting.
The solutions suggest setting an environment variable to define the host and port that works for your setup. For example:
process.env.FIRESTORE_EMULATOR_HOST = '127.0.0.1:5002';
You can find the correct host:port combination to use after you've fired up the emulators with firebase emulators:start
This has been addressed in the new modular v9 JS SDK, but does require a bit of refactoring to the new API (as defined in the docs). You can now specify the host and port when initialising:
testEnv = await initializeTestEnvironment({
projectId: projectId,
firestore: {
host: '127.0.0.1',
port: 5002,
}
});
PS. Don't also be fooled like I was by assuming that 127.0.0.1 and localhost are always the same!
The following is a simple test to get the OIDC token using gapi client
// example.spec.ts
test("get oidc token", async ({ page }) => {
gapi.load("client", () => {
gapi.client
.init({
apiKey: "*****",
clientId:
"********",
discoveryDocs: [
"https://iamcredentials.googleapis.com/$discovery/rest?version=v1",
],
})
.catch((err) => {
console.error(err);
})
.then(() => {
return gapi.client.request({
path: "https://iamcredentials.googleapis.com/v1/...:generateIdToken",
...
});
})
.catch((err) => {
console.error(err);
})
.then((token) => console.log(`OIDC token ${token}`));
});
});
It won't work as it raises a ReferenceError: gapi is not defined even though the #types/gapi are installed.
I've already tried to add "gapi"/"#types/gapi" in types inside the tsconfig.json file or import 'gapi' without any success.
Now I'm wondering if it is possible to use the gapi client from Playwright or not.
I am using ReactJS with Firebase to make functions. My motive is to create a user signup function. Following is the code for it.
app.post( '/signup', (req, res)=> {
const newUser = {
email : req.body.email,
password : req.body.password,
confirmPassword : req.body.confirmPassword,
handle : req.body.handle,
};
firebase.auth().createUserWithEmailAndPassword('newUser.email', 'newUser.password')
.then((data)=>{
return res.json({message: `user signed up successfully`});
} ).catch( (err) => { console.error(err); return res.json({error : err.code}) } );
} )
It also requires the use of Firebase initialization with proper credentials. The code i am including below :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
const firebase = require('firebase');
const firebaseConfigg = {
apiKey: "A*************************s",
authDomain: "socialape-9ede9.firebaseapp.com",
databaseURL: "https://socialape-9ede9.firebaseio.com",
projectId: "socialape-9ede9",
storageBucket: "socialape-9ede9.appspot.com",
messagingSenderId: "105*****9789",
appId: "1:1054747689789:web:075f037f03b59627edfb54",
measurementId: "G-ZY1LNR052N"
};
admin.initializeApp();
firebase.initializeApp(firebaseConfigg);
The firebase functions log is showing this error when i try to run firebase deploy :
How to get through this error? I have been following this youtube tutorial link :Youtube social networking website tutorial with react and firebase and around 42.55min the guy uses firebase authentication, and copies a code in project settings, which seems to be different for me (obvioously i am not expecting the same api keys etc, but the format, it actually asks me to add a web app, but not in the tutorial) when i go through the exact same steps, snippet for me looks like the const firebaseconfig that i gave in the code snippet above.
My VS Code says:
Error: Functions did not deploy properly.
In a Cloud Function, you need to use the Admin SDK if you want to interact with one of the Firebase services (Auth, Firestore, Cloud storage, etc.).
So, you need to adapt you code as follows:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
//...
app.post( '/signup', (req, res)=> {
const newUser = {
email : req.body.email,
password : req.body.password,
// see https://firebase.google.com/docs/reference/admin/node/admin.auth.UserRecord
};
admin.auth().createUser(newUser)
.then((data)=> {
return res.send({message: `user signed up successfully`});
})
.catch((err) => {
console.error(err);
return res.status(500).send({error : err.code}) });
});
See also https://firebase.google.com/docs/auth/admin/manage-users?authuser=0#create_a_user.
I am trying to follow a video on youtube called "Full Stack React & Firebase Tutorial - Build a social media app" and I am having trouble with the code for adding new users to firebase..
My code looks like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "socialtutorial.firebaseapp.com",
databaseURL: "https://socialtutorial.firebaseio.com",
projectId: "socialtutorial",
storageBucket: "socialtutorial.appspot.com",
messagingSenderId: "SenderID",
appId: "1:848457683801:web:a276f7436db03ac500b248"
}
const firebase = require('firebase');
firebase.initializeApp(firebaseConfig);
app.get('/challenges', (req, res) => {
admin
.firestore()
.collection('challenges')
.orderBy('challengeCreated', 'desc')
.get()
.then(data => {
let challenges = [];
data.forEach(doc => {
challenges.push({
challengeId: doc.id,
challengeName: doc.data().challengeName,
challengeDescription: doc.data().challengeDescription,
challengeCreated: doc.data().challengeCreated
});
});
return res.json(challenges);
})
.catch (err => console.error(err));
})
app.post('/challenge', (req, res) => {
const newChallenge = {
challengeName: req.body.challengeName,
challengeDescription: req.body.challengeDescription,
challengeCreated: new Date().toISOString()
};
admin.firestore()
.collection('challenges')
.add(newChallenge)
.then(doc => {
res.json({message: `document ${doc.id} created successfully`});
})
.catch(err => {
res.status(500).json({error: 'something went wrong'});
console.error(err);
})
})
//Sign Up Route
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
userName: req.body.userName
}
//TODO Validate
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res.status(201).json({message: `user ${data.user.uid} signed up successfully`});
})
.catch(err) => {
console.error(err);
return res.status(500).json({error: err.code})
}
})
exports.api = functions.region('europe-west1').https.onRequest(app);
Now, when I try "firebase deploy" or "serve" I get an unexpected token error. The error is the "." after firebase... I must have missed something in the code above, but I can't see it for the life of me. I know this is a stupid mistake and I should be able to fix it on my own, but I literally can't see, where the error comes from...
Any help from you guys? Thanks a lot in advance!
I'm not sure if maybe you copied pasted to the question incorrectly from your editor but the only thing I see is the last catch of your code. It seems you never pass a callback to it.
you defined it as follows
.catch(err) => {
but it should be
.catch(err => {
I have a script that I want to run through the Heroku CLI. It's just a simple script to create a user in a postgressql database with Sequelize.
This is the script:
const argv = require('yargs').argv;
const Sequelize = require('sequelize');
const sqlizr = require('sqlizr');
require('dotenv').load();
// Check params
if (!argv.username) { throw new Error('username is required!'); }
if (!argv.password) { throw new Error('password is required!'); }
if (!argv.clientId) { throw new Error('client id is required!'); }
// Init db connection
const sequelize = new Sequelize(
process.env.DB_DATABASE,
process.env.DB_USER,
process.env.DB_PASS,
{
host: process.env.DB_HOST,
port: 5432,
dialect: 'postgres',
logging: false
}
)
var client_id = argv.clientId;
if(argv.clientId === -1){
client_id = 0;
}
console.log(sequelize)
sqlizr(sequelize, 'api/models/**/*.js');
// Check if user exists
console.log('Check is user exists...');
sequelize.models.USERS.count({
where: {
USERNAME: argv.username
}
})
.then(result => {
if (result > 0) {
console.error('user already exists!');
process.exit(1);
}
})
.then(() => {
console.log('Creating user...');
sequelize.models.USERS.create({
USERNAME: argv.username,
PASSWORD: argv.password,
CLNT_ID: client_id,
EMAIL: 'email#email.com',
PHONE: '123456789'
})
.then(result => {
console.log('User created successfully!');
})
.catch(error => {
console.error('Could not create user!', error);
})
.finally(result => {
process.exit(1);
});
});
Everything goes well if I execute this command locally:
node bin/createUser.js --username admin --password admin --clientId -1
But If i try to run this through the Heroku CLI like this:
heroku run bin/createUser.js --username admin --password admin --clientId -1
I get this in the terminal:
bin/createUser.js: line 4: syntax error near unexpected token `('
bin/createUser.js: line 4: `const yargs = require('yargs');'
I can't figure out what I'm doing wrong here. Hopefully someone can help me and explain why this is happening
You forgot to specify node in the command, so I suspect that Heroku is trying to run createUser.js as if it were a shell script.
You may need to install a node.js buildpack to be able to run the program on Heroku, but try:
heroku run node bin/createUser.js --username admin --password admin --clientId -1