For example. I have an app that uses firestore, a couple functions, and hosting. Monthly I see about 2.5 million individual reads, 250k writes, and about 75k deletes. I get charged under $1.50/month on the blaze plan.
There is a pricing calculator on their website if you know around what your usage will be: https://firebase.google.com/pricing/
Just be smart with data fetching/updating on your site. Employ some caching on the front-end if you want and only use the snapshot updates when you absolutely need them.
Not really since firestore is not technically a sql database despite it having sql like features/queries, that being said probably the most important thing to do would be to make sure your "rules" are locked down. https://firebase.google.com/docs/firestore/security/get-started
use firebase realtime database and presence tracking. you can schedule code to run when a user is detected to be disconnected. how exactly that is defined, I'm not 100% sure.
https://firebase.google.com/docs/reference/node/firebase.database.OnDisconnect
You might want to look at App Check, which Firebase recently added. Combined with security rules, this gives you both broad protection against abuse, and fine grained control over the data access.
If the flutter sdk are anything like the web (which it looks like it is), this is totally fine. These keys are just used to identify your app with your project. Auth + Firebase security rules are what keeps things under lock and key. Would be nice if they explicitly stated this stuff in the docs (maybe they do and I missed it) but here Frank’s response to a similar question on SO
https://stackoverflow.com/questions/37482366/is-it-safe-to-expose-firebase-apikey-to-the-public
Edit: actually, looks like they do talk about including api keys in your code:
Storing info that the user already knows (subscription info) in custom claims is fine, IMO
There is a stripe extension that already does all of this btw https://firebase.google.com/products/extensions/firestore-stripe-subscriptions
Yes you're right, a 3GB database will cost you $10/month for storage. You're also right that $5/GB is very high! That's because Realtime Database is meant for small data sets and optimized for latency.
If you have a very large data set, try Cloud Firestore. It only charges $0.18/GB/month for storage which is 27x less than Realtime Database. But it charges more for some other things, like reads and writes in some cases.
See this document for a comparison:
https://firebase.google.com/docs/database/rtdb-vs-firestore
Well you don't, that's the reality. Till now it's not possible to query for a range on two different fields.
So you can't query Where lat > 14 and < 15 and long ...
There is a workaround with geo hashing
https://firebase.google.com/docs/firestore/solutions/geoqueries?hl=en
https://firebase.google.com/docs/reference/node/firebase.firestore.Timestamp This allows you to save a timestamp instead of using local dates
You could use cloud functions triggers for this. You essentially create an event listener that looks for user creation (on firebase) - the rest of the logic is up to you to do whatever you want (i.e. take the user's uid
, send it to your db).
So they're just unofficial versions of Firebase Extensions?
I store the original but then serve them back via an image proxy which resizes/optimises on the fly, and put that behind a CDN
This is the proxy is use: https://imgproxy.net
Hosted services like https://cloudinary.com do the same
Alternatively, you could create optimised/resized versions of the file when a user uploads using imagemagick or vips. Libraries are available for pretty much all languages. This is much less flexible than using an image proxy though.
Tough to answer for sure without more context about when/where your executing that call, but it could simply be an issue detailed in the Firebase docs:
> Note: currentUser might also be null because the auth object has not finished initializing. If you use an observer to keep track of the user's sign-in status, you don't need to handle this case.
The recommended way to get the current user is with <code>onAuthStateChanged</code>
The basic idea here is that once a user has created an account, they are assigned a unique identifier (uid). As they go to create/save a particular object in firestore, you'll want to add a field on the object that references their uid. I always have a "creator" field that gets filled with their uid. To retrieve the documents for a user you can use the firebase "where" query. It'll look something like...
docRef.where("creator", "==", uid);
You can read more about these queries here.
This doesn't prevent a user from querying another user's documents though. If they know the id of a particular object, they can just go and query for that. To prevent this, you'll need to configure your firebase rules to limit access based that "creator" field I mentioned earlier. There's an entire section in the documentation on firebase security.
When you deploy your function, they are dockerized into separate container images. Suppose you have 2 functions and when you deploy those functions each of those functions has a copy of your functions
directory. They both are converted into separate docker images and stored in container registry. While building these images they consume your Cloud Build minutes, it's free up to 120 minutes/day but the container registry (a special type of storage bucket used to store built docker images) is not free and charges around $0.26/GB.
You can see the pricing at: https://firebase.google.com/pricing
So when deploying your function you'll be charged for the storage cost of container registry and the storage bandwidth consumed equal to the size of those docker images.
Suppose if you've deployed an onUserCreate
function in us-central1
then you can see your container image in Cloud Storage through Google Cloud Console. You'll see a storage bucket with name something like gcf-sources-******-us-central1
, open this bucket and you should see all container images built for your deployed functions. Do not delete this bucket as Cloud Functions API handles this for you.
To view storage buckets in Google Cloud Console, visit: https://console.cloud.google.com/storage/browser
There's an official document from Firebase explaining how to set up Firebase hosting.
https://firebase.google.com/docs/hosting/quickstart?hl=en
You might want to go through this.
Hi not A computer. You can do what you're after all in on go. Since you are going to be doing a compound query, you'll need to create an index. This will allow you to create the query with multiple where clauses.
You can also specify to order the response as well as limit the response to a specified number of documents. I believe the billed amount should be the number of documents returned by your query. So in your example you should be billed for 10 reads.
Cloud functions and the admin SDK aren't necessary to have a secure and complex application that is only an SPA. For example, you can limit queries based on who created the record, limit reads based on user ids within an array on the document, limit document creation to only those who are authenticated, and more by securing your Firestore data with rules. There is a similar rules for using the realtime database.
Those rules get you very far. But payments for example are something you'll need to create a function for as you will have private tokens used to submit payments.
Thanks for the great blog post Pier!
On using the local emulator: did you give the functions shell a try? https://firebase.google.com/docs/functions/local-emulator#invoke_realtime_database_functions While it's not as simple to invoke e.g. RTDB/Firestore functions as the HTTP emulator, I find that I catch many problems before deploying with it.
Btw: I use cron-job.org for trigger functions based on time. While still not as good as having them built-in, it is definitely easier than setting up an app engine instance. :-)
Why not just calculate the leaderboard rankings when requested, and cache your firebase function output so that it doesn't have to do the full calculation for each request. https://firebase.google.com/docs/hosting/manage-cache
There is verifybeforeupdateemail: Sends a verification email to a new email address. The user's email will be updated to the new one after being verified.
firebase.firestore.Timestamp.fromDate
receives a Date obj
firebase.firestore.Timestamp.fromMillis
receives a number
​
https://firebase.google.com/docs/reference/node/firebase.firestore.Timestamp
Spend some time reading the docs or youtube guides, Firestore / Firebase has solutions for all of these things that are straight forward to implement.
Deny all read / write to Firestore, and just use the Admin SDK on your Cloud Function to communicate. https://firebase.google.com/docs/reference/admin
It's not so much about the amount of users but what they do. Google has a calculator and examples. Btw I have 5 MAU and 0$ Bill 😋
Just one should be enough "Simultaneous responses sent from a single database. ~100,000/second"
So I'm assuming you're saving the likes somewhere in a Firebase database. If so, yes this is possible. The high level overview is something like this...
There's a high level overview of the process here, and a more detailed example (that I haven't tried myself) here.
One project per environment. Three firebase projects in total: dev, stage, prod; each having its own resources. Firebase hosting supports multiple hosting targets. Main app, admin app, reports app are to be deployed to firebase hosting.
You can use a pub/sub function to run a function periodically. See the Scheduled Function section.
Then within the function, you can do the fetching and use the admin sdk to write the data to firestore.
You can use Pub/Sub and Cloud Scheduler to run functions on a schedule. Something as simple as functions.pubsub.schedule('every 1 days').onRun.
It handles everything for you behind that.
The code itself is simple. You can either construct a Date
object with your unix timestamp (with a little math converting it to milliseconds), or use a library like date-fns. Something like the differenceInDays
function there. Get the difference between your date and today. If it's >30, delete. That's the easy part.
You're comparing methods in two different SDKs.
Firstly, auth().updateProfile()
is actually auth().currentUser.updateProfile(). It's a method on User, not a top-level auth method. It's for allowing users to update their own profile information within your client app.
auth().updateUser() is a method provided by the Firebase Admin SDK, which runs on the backend, not in the client app. It's for writing backend code that also updates a user's profile. Since it runs on a secure backend, it allows administrative code to make changes to anyone's profile. It also has the ability to disable the account entirely.
My recommendation would be to use Firebase Admin. You'll have elevated privileges so you can do what you need to do, while closing off your storage or database rules to outsiders.
Firebase essentially runs the equivalent of this command to verify the TXT records:
dig -t txt +noall +answer yourdomain.com
If you get the expected results when you run this, wait for a few more hours. If verification doesn't continue after that, reach out to Firebase support for personalized help in troubleshooting.
Apparently, yes: https://firebase.google.com/docs/cloud-messaging/js/client
That page is pretty detailed with lots of code examples. If you have more questions ask and we'll figure it out. Did you try that and it didn't work? It involves getting a service worker up and running.
I'm not sure but firebase functions are just nodejs right? Quick google and found this; not sure if it works for your case, or for cloud functions at all.. but maybe give it a try
https://stackoverflow.com/questions/17811827/get-a-json-via-http-request-in-nodejs
Yes, RTDB uses unix timestamps as names
But firestore uses random ids, unless otherwise specified.
See https://firebase.google.com/docs/firestore/data-model
Or https://firebase.google.com/docs/firestore/manage-data/add-data#web-version-9_7
There's an extension that you can use that will resize images. You can read more about it here. It should be able to do what you need. https://firebase.google.com/products/extensions/firebase-storage-resize-images
unfortunately you aren't the first to complain about this 🤷♂️ a lot of people are frustrated with google for failing to give solo developers with no money (a lot of us!) a sense of security. join the "firebase anxiety" club :(
there are some basic things you can do to prevent malicious use of your resources, like enabling app check
what firebase services are you using? eg if you are using firestore, I think (don't trust me though!) that you could just disable all your security rules. should work because ingress is not charged ("Requests denied by your Firestore Security Rules do not count towards network bandwidth usage") and no documents are being read or written to.
You can use your custom backend which can provide JWTs in response to valid email and passwords (or whatever credentials your system accepts). You can use this custom auth token on your client to authenticate with firebase.
https://firebase.google.com/docs/auth/admin/create-custom-tokens
​
The benefit of this approach is that you can use security rules properly as would for normal Firebase auth users instead of locking down the database and invoking functions for every read/write (this can get expensive fast and you might face issues if using a lot of transactions and batch writes).
That's a bad idea. A bad usecase for remote config. You are going to have issue with the quota:
https://firebase.google.com/docs/remote-config/get-started?platform=android#throttling
Yes that's possible.
Let's say your current logic looks like that:
(note: the code example below are more pseudo code since I don't know all correct function names by heart)
allow write: if request.auth.uid == documentId
So you only allow user to write their own user document.
what you wann do is first step, be more specific and make a difference between create and update
allow create: if request.auth.uid == request.data.docName
so user can create documents but only if the document name is the same as their uid
Now lets make a more granular update rule:
On top level that will be an OR stmt:
allow update: if (request.auth.uid == docName) || (specific things for follower update)
what do we want to allow others?
- update one specific field
- only increment this specific field
for this we need those functions:
We wanna check that the only affected field is let's say "followersCount" we do that with the diff function:
request.resource.data.diff(resource.data).affectedKeys().hasOnly(["followersCount"]);
(here more details:
https://firebase.google.com/docs/reference/rules/rules.MapDiff#addedKeys)
and the second thing we want to check is, if it only adds 1
so we compare:
request.resource.data.followersCount - resource.data.follwersCount == 1
now let's put that in functions:
function onlyFollowerCounts() { return request.resource.data.diff(resource.data).affectedKeys().hasOnly(["followersCount"]); }
and
function diffIsOnlyOne() { return request.resource.data.followersCount - resource.data.follwersCount == 1 }
and add both to our update clause:
allow update: if (request.auth.uid == docName) || (onlyFollowerCounts() && diffIsOnlyOne())
That should be a working logic :)
So you want a search filter? Firebase can't make compound queries across collections and with multiple range fields. But take a look yourself, I haven't done that in production.
https://firebase.google.com/docs/firestore/query-data/queries
Trust me, there were a _lot_ of long meetings about why it had to go. It was great for a few use-cases, but it had some major issues (abuse was the big one). If you do hit a 10k bill from a ddos or a coding mistake, you can hit up https://firebase.google.com/support to get it ironed out.
Yeah db.collection is wrong. Check the update guide
https://firebase.google.com/docs/web/modular-upgrade
For example, first you create a collection reference:
import { getFirestore, collection, query, where, getDocs } from "firebase/firestore";
const db = getFirestore(firebaseApp);
const q = query(collection(db, "cities"), where("capital", "==", true));
const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots console.log(doc.id, " => ", doc.data()); });
You can't perform this query as-is. You can't do an inequality search (greater-than-or-less-than) on one field and then sort by another, even with custom indexes. (Docs)
What you can do is perform an equality on one field, and then sort by another. That requires a custom index, but the SDK will generally give you the URL to generate this index as an error message the first time you run it. So what you could do is create a "More than 300 kills" field and set that to true. Then you could go ahead and run a query like:
getDocs(query(collection(db, 'leaderboard'), where('more_than_300_kills', '==', true), orderBy('kdr', 'desc'), limit(100)))
Firestore is not a great pick for these types of queries.
The "solution" is to either use a client-side transaction, or calculate this with a cloud function every time a new friend is added.
> Cloud Firestore does not support native aggregation queries. However, you can use client-side transactions or Cloud Functions to easily maintain aggregate information about your data.
https://firebase.google.com/docs/firestore/solutions/aggregation
In my experience, if your project has reached a point where you're beyond the capabilities of Firestore, you should probably start thinking about moving to a real database like Postgres, Fauna, or even Mongo.
There are two methods: set
and update
. The difference is that when you use the set
method, you replace the whole document but when you use the update
method, you replace fields in the document.
https://firebase.google.com/docs/firestore/manage-data/add-data#update-data
It depends on how popular your documentation is. With hosting you have free data transfer of 360 MB/day. https://firebase.google.com/pricing
You can start with the Spark Plan without any risk of being billed.
Yes it's possible and here is how you can dot it:
set up the form and use Firebase hosting
add a callable Function which is called when the form is send
the function sends the email
This way your email code is in the server (the callable Function) and all email credentials are hidden from the client. The form data is sent to the function when you call the function. Of course with the function you could use any of the well known email sending services
Here are the docs:
Firebase Hosting:
Callable Function:
Hey check out this link and follow the instructions closely (read the whole page, but I linked you the firestore specific part):
https://firebase.google.com/docs/functions/local-emulator#cloud_firestore
Basically, you DO NOT need to change the code of index.ts at all, you just NOT deploy it but emulate it instead. But look I have never done it myself but am going to try it today or tomorrow as well. I am gonna share my experience here if you want
Yeah, I totally understand that. The fixed-price Flame plan was actually much more expensive for 90% of the devs that used it, than they'd pay on the pay-as-you-go Blaze plan. But the peace of mind was worth it to them.
Unfortunately not all caps were enforced in the Flame plan, and the abuse became prohibitive - so we had to remove that plan. It turns out that enforcing strict quota on distributed, global infrastructure is quite hard, especially when you also want to guarantee performance. We're still looking for ways to bring some sort of caps back, but so far nothing worked in a way we could roll out.
If you ever do see abuse or otherwise unexpectedly large bills, always reach out to Firebase support for personalized help in troubleshooting. Nobody should suffer because of an honest mistake, and our team is usually quite reasonable in such scenarios. We just can guarantee anything, because.... again.. abusers. 😕
Use a Firebase Function which is triggered when a document is created in the collection (e.g. in orders)
This function uses all the information from the document which triggered it and sends an email.
Here is the doc:
https://firebase.google.com/docs/functions/firestore-events?hl=en
And here is an example for sending emails:
https://github.com/firebase/functions-samples/blob/main/quickstarts/email-users/README.md
There is no secure way to send messages directly from within your application with Firebase Cloud Messaging, as that would allow anyone to send any messages they want to all your users - which is a security risk.
The simplest way to send messages from the app is through Cloud Functions, as that is then where you'd secure access to ensure only authorized users can send messages you deem acceptable.
I think we can just useauth().createCustomToken()
inside a firebase function and return the token to the user? Reference Documentation: Create Custom Tokens
For more detail, the process inside this login firebase function, will be something like, first, validate, and authenticate the Email/ID/Token with appropriate logic to ensure user is really 'logged in' to Plex, and next, create a custom token with JSON claims (optional) of any information you want to use for authorization in your RTDB security rules, and return the token. In the client, just call signInWithCustomToken()
with the token to complete the login.
You can also check out this documentation:
https://firebase.google.com/docs/projects/billing/avoid-surprise-bills
It has some basic ways to avoid billing surprises and there is even more documentation on ways to listen for billing events and act on them, like removing billing at a certain point in the advanced billing alerts documentation
Firebase authentication is what allows your client to authorise with your Firebase backend. This authorisation process is almost entirely automatic, you don't even need a server.
The documentation you quoted simply states that your sever (should you chose to have one) doesn't need to authenticate with Firebase because it doesn't need to (the server automatically has authenticated access).
If you would like to authorise your client using your own authorisation technique, you can let your server generate custom tokens and use those to authenticate instead. More info here
When you call onSnapshot
it returns a function. When you call that function, it unsubscribes the listener from updates. So in JavaScript from the documentation un unsubscribing listeners:
var unsubscribe = db.collection("cities")
.onSnapshot(() => {
// Respond to data
// ...
});
// Later ...
// Stop listening to changes
unsubscribe();
The call to unsubscribe
can be anywhere where that variable is in scope so also inside the onSnapshot
callback.
you can try looking into this:
https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect
once the firebase servers detect that the client is no longer connected (closes window, drops internet connection, etc), it will execute a block of code.
this only works with the RTDB, not firestore. but I think you can still use it if you set up RTDB just for using onDisconnect.
For an example of this, see the Firebase documentation on securing content-owner only access. The rules shown there:
service cloud.firestore {
match /databases/{database}/documents {
// Allow only authenticated content owners access
match /some_collection/{userId}/{documents=**} {
allow read, write: if request.auth != null && request.auth.uid == userId
}
}
}
The request.auth.uid == userId
in there ensure that each user can only access therir own document (and subcollections under that document) in the collection in match /some_collection/{userId}
.
Yeah definitely, I’d add some middleware to your express server to check the user is verified. You can do this using the id token in the auth library on the client, and then use the admin sdk to verify the token. This is the article you want: https://firebase.google.com/docs/auth/admin/verify-id-tokens
You can write data queries using Firebase, like:
let matchedUsers = usersRef.where("score", ">=", 10)
You can call a function directly like using the functions.https.onRequest
Here is how it will look like in your NodeJS application:
export.matchMake = functions.https.onRequest((req, res) => {// Enter code to read from db});
You can also reference the documentation for morehttps://firebase.google.com/docs/functions/http-events
No risk, in fact email and phone number are already present in the standard Firebase token claims - docs, no need for custom claims. I’ve linked to sever docs here but you can get this same decoded token on the client with user.getIdTokenResult().
Hey mate, we can use a query here.
https://firebase.google.com/docs/firestore/query-data/queries
in this scenario, we'd do this;
db.collection('patients').where('emailField','==', email).get()
Message me if you have any problems and I'll be happy to help out.
Firebase Functions can host HTTP functions and it's pretty easy to handle them with an Express app.
Firebase even has documentation for this: https://firebase.google.com/docs/functions/http-events#using_existing_express_apps
As others have commented, Firebase Authentication is completely free of charge for all plans with the exception of Phone authentication.
However, there are some limits (pretty generous to be honest) that you may want to be aware of: https://firebase.google.com/docs/auth/limits
For Cloud Firestore there's a minimum of one read, even if no results are returned: https://firebase.google.com/docs/firestore/pricing#minimum-charge
So it looks like the only thing you might gain from running the versioned query is not being charged for reads originating from security rules (as long as it's a get on the query and not a listener).
You will need to create a function to validate on your own the data provided, then, use the auth admin api to create a custom token and send back to the front, to signIn with.
Something like that.
You're charged for reads of each document that happen on the server, not for those that happen from the client-side cache.
But if you start a new query with the default settings, the server will need to read each document to check if your cache is up to date. To prevent that, you can run the query with the option to only access the cache, or keep your query listening for longer (as in that case the server will inform the client right away when there's an update).
What i gotta from here, https://firebase.google.com/docs/auth/admin/manage-sessions is Firebase Auth works with two tokens. It says:
```Firebase ID tokens are short lived and last for an hour; the refresh token can be used to retrieve new ID tokens. Refresh tokens expire only when one of the following occurs:
So, my Firebase ID token lives for 1 hour and the refresh token is used to update it. I`m i right? I`m assuming it is correct.
The local cache should prevent reads from getting out of control in this case.
https://firebase.google.com/docs/firestore/manage-data/enable-offline
You need to set up roles. Then, use firebase functions for the create accounts. The reason to use functions is so that you can do a test to see if the person submitting it has the admin role. You should, of course also hide the create account button based on roles too.
https://firebase.google.com/docs/firestore/solutions/role-based-access
Hey there, author of the example you used here. Totally legal, though you should look at Stripe's Integration Security Guide and make sure you understand all the points https://stripe.com/docs/security
> Stripe returns non-sensitive card information in the response to a charge request. This includes the card type, the last four digits of the card, and the expiration date. This information is not subject to PCI compliance, so you are able to store any of these properties in your database. Additionally, you can store anything returned by our API.
You should definitely have a terms of service + privacy policy for any web service you create.
Also make sure to use the database rules to ensure access level / integrity ;)
u/rustamd completely understand your concerns about which permissions we ask.
You are correct in that we ask for these permissions to streamline the process to truly make it a one-click install for functions. However, if you wanted to avoid giving us the permissions necessary, you can still sign up and download the source code directly.
Here is a link on how you can do that. For paid functions, you just need to pay for the function before you can see the source code to replicate the same process. If you run into any issues please reach out!
Also, would love to hear your thoughts on what it would take for you to feel comfortable in sharing those permissions to streamline the process of installing new cloud functions.
How to Download Source Code: https://www.loom.com/share/bfee1b3ee4cd424991aa8356a3c3095b
By ensuring that the user only has access to the parts of the database they're authorized to, you can prevent them from downloading the entire database by simply performing a read at the root.
I'm actually not sure how the "repeatedly" could be prevented for read operations though. For write operations it is definitely possible to implement a write rate-limit per user, as shown here for Cloud Firestore. But as far as I know, there is no way to do the same for read operations.
So while you can restrict what data a user can read through security rules, there is no way to restrict how often they can read it. If you think your app is seeing that type of abuse, reach out to Firebase support for personalized help in troubleshooting.
There is no way to log information from security rules, and nobody is actively working on it at the moment as far as I know. I'd definitely file a feature request for it though, as it could be really useful.
I personally often encapsulate pieces of functionality in individual functions, which I then call from the rules themselves. This makes it relatively easy to enable/disable them to figure out where a problem, especially when combines with the emulator where you can often more easily feign conditions.
I'd also highly recommend checking out the emulator suite, which often makes it a lot faster to test (changes to) your rules.
I recommend you to move your writes operations to a cloud function or any backend solution you use and do any validation you need there.
For more details about what is supported by security rules take a look at this, they always mention the fact that they are not filters and there is a good video on youtube that says something like if the rule can potentially fail it will fail
, so... play safe :).
You can't only allow select IP's, but you could deny all access to Firestore using rules. The admin SDK ignores any rules, so using it via Functions will still allow you to write to Firestore.
I would have a separate posts collection that isn't under the user because I'm imagining a use case where you need to get all the recent posts regardless of who created them. Similar to how reddit works.
The idea here is that whenever a user creates a post, you add a "creator" field to the post object which is the uid of the user that creates the record. If you need to fetch a user's posts then you can query with a <code>where</code> clause. Then finally, to secure your data, you can correlate that same creator field with the logged in user by using firebase security rules.
You can use Firebase's security rules to determine what data a user can write and read. Since these rules are run on the server, there's no way for your users to avoid them. For more on this, see: https://firebase.google.com/docs/firestore/security/overview You have full access to the user who is performing the write, through the `request.auth` variable.
I have never programmed on a MKR1000 board. But if your using an iot device/headless server then you need to use firebase admin sdk. Firebase admin sdk supports node, python, java and go. If you can run any of these programming languages things are easier for you. What you need to use is service account to authorize firebase authentication. https://firebase.google.com/docs/admin/setup If you cannot use admin sdk for auth then use the REST api for authorization https://firebase.google.com/docs/reference/rest/auth/
why would you have to duplicate data?
firestore:
posts/{postID} all the post data
realtime database:
postRankings/${postID} only the rating data
but I do suggest using a cloud function to watch for updates and perform a transaction to calculate the rankings (https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions) and realtime database isn't gonna care how many reads and writes it does, and cloud functions are extremely cheap, about $0.40 per million invocations...
> As far as I know RealTime database stores everything as type string...
It doesn't. See https://firebase.google.com/docs/firestore/manage-data/data-types. I didn't understand the rest of your question, though.
get()
only gets the data once, the current value.
addSnapshotListener(...)
will get and call with the current data but also then fire again with the new value whenever the data changes.
It's the realtime part of Firebase ;) Check out our docs here https://firebase.google.com/docs/firestore/query-data/listen
> The free plan is good to 100k simultaneous users. So 10k, even if online all at once, is perfectly fine.
According to https://firebase.google.com/pricing/ the maximum simultaneous user for the free tier is 100 and not 100k
If you use Firebase anonymous authentication then the user will have a id, which you can validate against. They will be effectively "logged in" https://firebase.google.com/docs/auth/web/anonymous-auth
I'm not an expert by any means, but I have been using Firebase for about a year and learning as I go.
Firebase functions: Yes, you can use them with ajax requests, but the real beauty is in database triggers. So fire this function when data is added to the database in this spot and then do something else with the data. I'm not sure if they "replace traditional frameworks" but it's node environment and you can add modules.
Firestore: I haven't used Firestore yet so can't comment. Keep in mind, Firestore literally came out like last month so I imagine there will be some rapid growth on that over next few months. I would suggest using the real-time database to get started since that's the product that made Firebase.
It sounds like you've missed possibly the most powerful thing in Firebase! Database rules: https://firebase.google.com/docs/database/security/ Since database query's happen in front-end, you need to be sure to lock down all of your data with database rules. It is very powerful, you can lock down to authenticated users, and specific user id, etc. Also, there is validation on the data before being put in db, etc...
Yeah they changed the way Firebase is set up. Here is the upgrade guide, specifically for the database references: https://firebase.google.com/support/guides/firebase-web#get_a_database_reference_numbered
This is the guide to connect https://www.notion.so/cuthanh/How-to-get-my-credential-file-781fb9bfa0cf479a81b72a272728808c
Yes that's what I meant. If you want to send individual messages to a user you have to store the token somewhere.
https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-specific-devices
Or you send it to a topic and therefore to all users which subscribed to this topic:
https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-topics
tldr: you#d need to serve your content via cloud functions:
https://firebase.google.com/docs/hosting/functions#connect-functions-to-hosting
That's not possible with Hosting (or not directly)
With Firebase Hosting you serve static files.
What you can do is: serve an empty html file with javascript and the javascript checks if it's an user, which user etc., and makes an authenticated call to the Backend, for example Firestore, to get the protected content. After that, javascript repaints the page in the browser to show the content.
That's a SPA.
If you don't want to do that you have use Cloud Functions: The Cloud Function gets the request, checks the authentication and sends the HTML back.
That would be SSR - server side rendering (you can do it manually or use frameworks like next.js)
OR if all your pages are static and already coded you simply check the user and return the html code of the page.
How can you still use Firebase Hosting?
You can connect a function to a hosting URL
You can use collectionGroup
but you have to know the names of each collection (regardless of depth). Also if you're looping everything you will probably hit the time out on the Cloud Function container. You should look at the <code>startAt/startAfter</code> methods so you don't start from 0 when you hit an error or container timeout.
Ok thanks, I decided to create a collection and loop through all the documents in the collection since I found the documentation on how to do that however my code doesn't like the await before calling getDocs(). I get the error message "Unexpected reserved word 'await'."
you can use the different subdomains. You'll want to add each domain to the respective capabilities and xml files. You should be able to follow these walkthroughs, just use a different domain for each
​
You could do this with triggers. Every time a document in your “songs” collection is created/updated you get enough data to write a new line to “activity”. This way you can keep your activity collection locked and only update it from the backend.
Oh, thought you were trying to diagnose what you did wrong. If you just want to shut down your database to only be accessible by authenticated users, use the rules here: https://firebase.google.com/docs/rules/basics#all_authenticated_users
(I would have copied & pasted the rules for you, but for some reason I'm not able to paste more than one line at a time in the Inline Code...so a link is easier :) )
Cloud functions have imagemagick baked into the container, so it should be pretty trivial to use that to create a thumbnail:
https://firebase.google.com/docs/storage/extend-with-functions#example_image_transformation
​
In order to backfill all of your current images, you'll need to write a separate function that just takes in the path of each of your pre-existing assets, and run a batch job to process all of those. If written properly, you should be able to simply (and elegantly) re-use a good chunk of the code for resizing newly uploaded assets.
Someone else was able to answer this for me - data validation https://firebase.google.com/docs/storage/security#data_validation
Thanks tho!
not sure I really understand your question but I think this is what you need, after the user sign in on front end, send the id token to your back end(any back end) and verify it
https://firebase.google.com/docs/auth/admin/verify-id-tokens#web
A common solution is cache-busting. It essentially adds a suffix to your loaded static files forcing browsers to load them from the server as they think it's a totally new file. You will need to use a bundler like Webpack or Gulp in order to automate the process and update links. However I'm sure a quick Google search should turn up lots more ways of going about it that may suit your needs better.
The only thing this doesn't necessarily work for is loading the HTML files. For SPA apps you can set the served index.html to never be cached using max-age headers in the firebase config. Even if you have seperate html files for every page I still think it is worth considering not caching on the browser side since Firebase already hosts a very fast CDN and the HTML file is usually very small compared to JS, CSS and images. But of course your mileage may vary!
Just this https://firebase.google.com/docs/functions/callable. But it’s has nothing to do with the databases. If you want to interact with Firestore or RTDB directly in the front end, you’ll use Security Rules to set up permissions.