Firestore not reflecting changes in firestore after deployed - javascript

I have a web app written in NUXT that makes use of Firebase's Hosting, Firestore, Authentication and Storage.
Its a simple blog layout that has all the usual CRUD functions for its blog posts. It is loosely bases on Quick Nuxt.js SSR prototyping with Firebase Cloud Functions and Nuxt.js Firebase Auth.
In the development environment it runs perfectly but when I deploy it, the Firestore specifically, behaves unexpectedly.
So after the project has been deployed I can CRUD documents that reflect as expected in the Firebase Console Firestore viewer, but when I read the data again it will load the same data. In other words if I delete a document it will disappear in the Firestore viewer but when I refresh my NUXT website it loads that document again even though it's no longer present in the Firebase console. I get the same result on different computers/devices, so not a local caching issue.
I noticed that the changes in the Firestore viewer will only reflect in my website after I re-deploy my project. But any changes I make will not show after I refresh the website even though they have changed permanently in the Firestore viewer.
When in development it works perfectly, I can manipulate the database, refresh and it will load exactly what’s reflected in Firestore viewer.
Sorry for repeating it so much but I’m having an existential crisis here, lol.
So below is a sample of the NUXT's Store's index.js file, where you would have all your data stored for your app. It works perfectly at manipulating the data on Firestore but once in production the website gets served the same data over and over.
import { firestore } from '~/plugins/fireinit.js' // the part where `firebase.initializeApp` happens
Decare my array state: posts.
export const state = () => ({
posts: []
})
Mutations for manipulating the posts array.
export const mutations = {
addP (state, payload) { // Gets run for each documents from collection on first load.
state.posts.push(payload);
},
delP (state, payload) { // Deletes a post from the posts state.
state.posts = state.posts.filter(p => {
return p.id != payload.id;
});
},
}
The nuxtServerInit() runs on the server to make it Server Side Rendered when the website first loads.
export const actions = {
async nuxtServerInit({commit}, context) {
await firestore.collection('posts').get().then((querySnapshot) => {
querySnapshot.forEach(function(doc) {
var obj = doc.data()
obj.id = doc.id;
commit('posts/addP', obj)
})
})
},
The deletePost() action deletes a file on Firebase Storage then deletes the document on Firestore. Then finally removes the item from the posts state.
deletePost ({commit}, payload) {
storage.ref().child(payload.fullPath).delete().then(function() {
firestore.collection('posts').doc(payload.id).delete().then(()=>{
commit('delP', payload);
})
.catch((error)=>{
console.error(error);
});
})
}
}
This is what my Firestore Rules look like
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read;
allow write: if request.auth != null;
}
}
}
What am I doing wrong :/

So after losing some hair I finally figured it out!
So in NUXT you have two options for deploying your project, nuxt build or nuxt generate.
The generate option reads the database and then builds your static files from the firestore, which is then deployed. This is why when I reloaded my page it had all the old entried in the DB.
After switching to the build option and deploying that instead it all works perfectly.

Related

Watermelon Sync With Firebase

I'm wanting to use watermelon sync with Firestore but I'm not getting it. I do not even know where to begin with. I'm not using API. I want to do it only in React Native. I want to sync my app offline and online. Can someone help me??
Im using React Native to do That...
import { synchronize } from '#nozbe/watermelondb/sync'
async function mySync() {
await synchronize({
database,
pullChanges: async ({ lastPulledAt, schemaVersion, migration }) => {
const urlParams = `last_pulled_at=${lastPulledAt}&schema_version=${schemaVersion}&migration=${encodeURIComponent(JSON.stringify(migration))}`
const response = await fetch(`https://my.backend/sync?${urlParams}`)
if (!response.ok) {
throw new Error(await response.text())
}
const { changes, timestamp } = await response.json()
return { changes, timestamp }
},
pushChanges: async ({ changes, lastPulledAt }) => {
const response = await fetch(`https://my.backend/sync?last_pulled_at=${lastPulledAt}`, {
method: 'POST',
body: JSON.stringify(changes)
})
if (!response.ok) {
throw new Error(await response.text())
}
},
migrationsEnabledAtVersion: 1,
})
}
the example above is the code shown on the Watermelon website. But I want to do it without using API! Only with React Native and Firestore/firebase. How could I do this in react Native, and whenever there is any change in the application it automatically saves it in the database when the user is connected to the internet? My app is Offline Frist
There are some packages that helps with syncing react native to firebase and you won't need to build your own backend server and apis. To quote from the watermelondb docs.
MelonFire, a React Native library to sync your database to Firestore. MelonFire overcomes common bugs in implementations (e.g. timestamp jitter, multiple writers, Firestore's 500-write transaction limit, retries) to guarantee database consistency.
Firemelon, an alternative implementation to sync your database to Firestore. It relies on changes being smaller than Firestore's 500-write transaction limit, and doesn't handle server timestamp intricacies, but supports ignoring certain tables when backing up.
Hope this helps.

404 Page not found Vercel Deployment - using dynamic routing in Next JS

I am making a full-stack web-application using Next JS where I allow the user to create and manage letters (applications) based on pre-defined templates. So when the user successfully creates an application, it is sent to the database (POSTGRES) which is hosted on Supabase. On the home page, the applications created by the user are fetched and displayed in the form of a list. Here on, when the user chooses to preview an application, dynamic routing is put in place where the application IDs work as the dynamic parameter. By using getStaticPaths() to get the route parameters from the database, and then fetching the data for the page from the database based on the application ID in the getStaticProps() method at build time, we render the page. It works seamlessly on localhost but not on Vercel. The interesting part however is,that dynamic routing works on Vercel for past applications for every deployment, that is if the user wants to preview their past applications they can do so without any problem, but when they create an application and then try to preview it, they are prompted with the 404 error. But if I trigger a redeployment either manually or by a commit to the main branch of my repository, the error is fixed for the particular application which was giving the error. `
export const getStaticPaths = async () => {
var APIendpoint;
if (process.env.NODE_ENV === 'development') {
APIendpoint = 'http://localhost:3000/api/fetchApplication'
}
else if (process.env.NODE_ENV === 'production') {
APIendpoint = 'https://templaterepo.vercel.app/api/fetchApplication';
}
const data = await getPaths(APIendpoint)
const paths = data.map((application) => {
return {
params: { id: application.appid.toString() }
}
})
return {
paths,
fallback: 'blocking'
}
}
export async function getStaticProps(context) {
const appID = context.params.id;
var APIendpoint;
if (process.env.NODE_ENV === 'development') {
APIendpoint = 'http://localhost:3000/api/fetchApplicationwithID'
}
else if (process.env.NODE_ENV === 'production') {
APIendpoint = 'https://templaterepo.vercel.app/api/fetchApplicationwithID';
}
let data = await getPageData(APIendpoint, appID);
return {
props: { data }
}
}
Here is the code for the dynamic [id].js page where in I first get the paths based on the application IDs and then in the getStaticProps() function I fetch the data for the page corresponding to the application ID at build time. It works as expected in localhost but in Vercel deployment, even before the functions are executed, I get a 404 error.
Note: Vercel Framework Preset is set to Next.js.
I tried a variety of solutions including adding to and as parameters in the Link component. Also I changed my vercel.json file to the below configuration
`
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
`
But nothing seems to work.
When they create an application and then try to preview it, they are
prompted with the 404 error. But if I trigger a redeployment either
manually or by a commit to the main branch of my repository, the error
is fixed for the particular application which was giving the error.
This is expected, the data necessary for each dynamic page to be built is fetched ONLY at build time. Since you are using getStaticProps, you can implement ISR by adding a revalidate prop in getStaticProps, that way when a page (like a new application) has not been generated at build-time, Next.js will server-render it on first request and then cache it for subsequent requests.
On development mode, both getStaticProps and getStaticPaths run per-request (much like getServerSideProps), that's why you don't have this issue on the dev environment. Reference to this on the docs.
If you decide to implement ISR and want to display a loading UI while the page is being server-rendered, make sure to set fallback: true on getStaticPaths and at component level, you can access the router.isFallback flag to display the loading UI accordingly, otherwise, leave it as you already have with fallback: 'blocking'.
Also, make sure you write the server-side code directly in getStaticProps and getStaticPaths instead of calling your own API endpoints on these functions. This according to the docs.

Create multiple Firebase Instances for the same project in Node.js

I have a Node.js server, inside which I want to have two firebase instances.
One instance should use the JavaScript SDK and will be used to provide authentication - login/register. The other instance should use the Admin SDK and will be used to read/write from the Realtime Database. I want to use this approach, so that I don't have to authenticate the user before each request to the Realtime DB.
I've read how we're supposed to initialize Firebase instances for multiple projects, but I'm not sure if my issue isn't coming from the fact that both instances are for the same project.
My issue is that I can use the JS SDK without any issue and I can login/register the user, but for some reason I can't get the Admin SDK to work.
Here's how I'm instantiating the apps:
const admin = require("firebase-admin");
const { applicationDefault } = require('firebase-admin/app');
admin.initializeApp({
credential: applicationDefault(),
databaseURL: 'my-database-url'
}, 'adminApp');
const firebase = require("firebase/app");
firebase.initializeApp(my-config);
Now I can use the JS SDK without an issue, but not the Admin SDK. I've created a test endpoint to just get data from my Realtime DB:
app.get("/api/test", (req, res) => {
const uid = 'my-user-UID';
admin.database().ref(`users/${uid}`)
.once('value', (snapshot) => {
if(snapshot) {
console.log('data');
} else {
console.log('no data');
}
});
});
Now here as an approach to getting the data from the Realtime DB, I tried all possible described approaches. Using get with child and all sorts of possible combinations. Here's an example of another approach I used:
get(child(ref(admin.database()), `users/${uid}`)).then((snapshot) => {
if (snapshot.exists()) {
// retrieved data
} else {
// No data
}
}).catch((error) => {
console.error(error);
});
For the first approach I wasn't getting any response at all, like the once wasn't executing. For the second one I think I was getting - typeerror: pathstring.replace is not a function firebase. At some point I was getting a no firebase app '[default]' has been created . These errors don't worry me as much, but since I saw the last error I moved my focus to the initialization of the apps, but still to no avail.
I just need a direction of where my issue might be coming from.
Update:
The solution is to not pass a second argument (app name) to any of the Firebase initializations. Looks like it's not needed in case you're referencing the same project.

Want client-side Firebase logs to show up in StackDriver, not users' browsers

I'm using firebase-functions/lib/logger to log client-side firebase/firestore activity like
const { log, error } = require("firebase-functions/lib/logger");
export const addData = async (userId, dataId) => {
try {
const collectionRef = firestore
.collection("docs")
await collectionRef.add({
dataId,
});
log(`Data added`, { userId, dataId });
} catch (err) {
error(`Unable to add new data`, { userId, dataId });
throw new Error(err);
}
};
When I run this on my local, the log shows up in my browser console. Will this happen on non-local environments, ie for real users? Will these logs also show up automatically in Stackdriver, or are they stuck on the client side? I want to be able to view the logs either in Stackdriver or Firebase console but have them not show up in the browser for real users. How should I accomplish this?
Messages logged in Cloud Functions will not show up in the client app at all (that would probably be a security hole for your app). They will show up in the Cloud Functions console in the log tab, and in StackDriver.
Any messages logged in your app will not show up in any Google Cloud product. They are constrained to the device that generated them. If you want cloud logging, you'll need to implement some other solution. Cloud Functions does not support this - you will need to investigate other solutions or build something yourself.

Firebase functions with AdminSdk and RealtimeDatabase not working

I'd like to create, edit, read and delete on the RealTime Database using the firebase functions. Looking at other similar questions I saw that the AdminSdk has to be used, and so I did.
I basically copy/pasted the code provided by the same firebase guides.
const admin = require("firebase-admin");
const functions = require("firebase-functions");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
const db = admin.database();
db.ref("devices")
.once("value")
.then(snapshot => console.log("Snapshot: ",snapshot.val())
.catch(error => console.log(error))
});
In the initialization I set the credential with applicationDefault() as I previously set the GOOGLE_APPLICATION_CREDENTIALS env variable with my service_account_key.json path.
I tried anyway to set it with the cert method and the result didn't change. As 3 accounts are showed in the Service account section I tried with all of them as well.
This said,when starting the functions from console with 'firebase serve' the log is not showed and no error either.
Is there anything I'm missing? Some further configuration or whatever error you might be aware of?
Thank you in advance!
Update following your comments:
You want to "create, edit, read and delete on the Realtime Database using Cloud Functions", as indicated in your question, mimicking the behaviour of a Client SDK but from a server that you control. You should use one or more Cloud Functions that you call directly from this server. The most appropriate (based on your comments) would be to use an HTTPS Cloud Function.
For example you could have an HTTPS Cloud Function like the simple one below, to write to a specific node of the Realtime Database, as follows:
exports.writeToNode = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const dbNode = req.body.nodeRef;
const objToWrite = req.body.nodeValue;
return admin.database().ref(dbNode).push(objToWrite)
.then(() => {
return res.send("Node " + dbNode + " updated!");
})
.catch(err => {
//please watch the official video https://www.youtube.com/watch?v=7IkUgCLr5oA&t=1s&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=3
});
});
});
You would call it by issuing a POST to the following URL https://us-central1-YOURPROJECTID.cloudfunctions.net/writeToNode, with a body like:
{
nodeRef: 'theNode',
nodeValue: {
firstName: 'John',
lastName: 'Doe'
}
}
Initializing the Admin SDK:
If you want to interact, from a Cloud Function, with the Realtime Database that is in the same Firebase project, you just need to initialize the Admin SDK without any parameter (i.e. admin.initializeApp();)
This way, the Admin SDK will use the Project's default service account, and will have full access to the Realtime Database (i.e. bypassing all the security rules).
So, initialize as follows:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
///// Additional thought /////
Note that you could maybe use the REST API exposed by the Realtime Database, instead of developing an entire set of CRUD endpoints through Cloud Functions. See https://firebase.google.com/docs/database/rest/start
REMAINING PART OF THE CONTENT OF THE INITIAL ANSWER, about background triggered Cloud Functions
You then need to declare a Cloud Function, as shown in the example below, by:
Selecting an "event handler";
Specifying the database path where it will listen for events and;
Executing the desired logic (normally using the data that was written at the path, or indicating that the node was deleted, etc...)
exports.makeUppercase = functions.database.ref('/devices/{pushId}/original')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
console.log('Uppercasing', context.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return snapshot.ref.parent.child('uppercase').set(uppercase);
});
This code snippet, copied from the documentation, will listen to any new node created under the devices node and will create an uppercase node the value of the original node in uppercase.
Note that this is a background triggered Cloud Function which is triggered when something "happens" at the specific path.
If you want to "create, edit, read and delete on the RealTime Database", as indicated in your question, mimicking the behaviour of a Client SDK, you may define one or more Cloud Functions that you call directly from your App. See the Callable Cloud Functions documentation.
You may alse read the following documentation items https://firebase.google.com/docs/functions/get-started and https://firebase.google.com/docs/functions/database-events and also watch the video series: https://firebase.google.com/docs/functions/video-series

Categories

Resources