Firebase Remote Config allows developers to control the appearance and the behaviour of their apps without having to publish an app update. You can build your app with in-app default configurations and later change those configurations by updating your project’s Remote Config template.
We are happy to announce that you can now manage your Remote Config templates directly from the Admin Node.js SDK.
Typically, you would use the Firebase console to specify and update Remote Config templates manually. However, sometimes you need more automation and server-side control of these settings, such as scheduling Remote Config updates or importing configurations from your own proprietary systems and other Firebase projects. Until now the Remote Config REST API was the only way to implement such use cases, which at times could be cumbersome.
As of version 8.13.0, the Admin SDK introduced a Remote Config API that simplifies the process of creating, accessing, and updating your Remote Config templates from your own backend servers and also from managed Cloud environments like Google Cloud Functions.
Let’s go through some examples on how to use the Firebase Admin Node.js SDK to manage your projects’ templates. You can start by creating a fresh Remote Config template for your project, or you can get the current active template and make changes to it. Here's how you can get the current active template in Node.js:
const admin = require('firebase-admin'); admin.initializeApp(); const template = await admin.remoteConfig().getTemplate(); console.log('ETag from server: ' + template.etag);
Each Remote Config template version is associated with an entity tag (ETag) for version control purposes. The Remote Config API uses this ETag to prevent race conditions and concurrent updates to resources. To learn more about ETags, see ETag - HTTP.
Once you have obtained your current active Remote Config template you can start making modifications. Here are some of the operations you can perform using the Admin Node.js SDK:
Let’s go through an example on adding a new Remote Config condition and a parameter to your template.
// add a new condition template.conditions.push({ name: 'android_en', expression: "device.os == 'android' " + "&& device.country in ['us','uk']", tagColor: 'BLUE' as admin.remoteConfig.TagColor, }); // add a new parameter, that references the above condition template.parameters['header_text'] = { defaultValue: { value: 'A Gryffindor must be brave, talented and helpful.' }, conditionalValues: { 'android_en': { value: 'A Droid must be brave, talented and helpful.' }, }, };
The above example creates a new condition named android_en and uses it in a conditional value of the parameter named header_text. Checkout the documentation to learn more about conditional expressions. Keep in mind that the conditions in a template are listed in descending order by priority. A parameter might have several conditional values associated with it. If multiple conditions evaluate to true, the first condition in the list takes precedence.
android_en
header_text
Once you make updates to your template you must publish it to make the new changes effective. After you publish a Remote Config template using the Firebase Admin Node.js SDK, that template becomes the current active version of your project. Before you publish a template you can always validate it to check for any errors.
try { const validatedTemplate = admin.remoteConfig() .validateTemplate(template); const publishedTemplate = admin.remoteConfig() .publishTemplate(validatedTemplate); } catch(err) { console.log('Error publishing the template:', error); }
For more details and code samples on programmatically modifying Remote Config templates, check out the detailed documentation.
In addition to the API for modifying Remote Config templates, the Firebase Admin Node.js SDK provides an API to manage Remote Config template versions. This API supports the following operations.
The listVersions operation allows you to retrieve a list of metadata for all stored versions of your project, sorted in reverse chronological order. Note that the last 300 versions are stored. All versions that correspond to non-active Remote Config templates (that is, all except the template that is being fetched by clients) are also deleted if they are more than 90 days old. Here’s a sample code to fetch a list of template versions.
listVersions
// list all the Remote Config template Versions // Only the last 300 versions are stored. const listVersionsResult = admin.remoteConfig().listVersions(); listVersionsResult.versions.forEach((version) => { console.log('version', JSON.stringify(version)); });
For a complete list of available operations and examples, check out the documentation on programmatically managing Remote Config template versions.
We hope this new addition of the Remote Config API in the Admin Node.js SDK helps with your backend development tasks. Stay tuned for the Remote Config API to be added across other Firebase Admin SDK platforms. We are excited to see how you use the new APIs in your projects! Hop over to our Github Repo to check out the implementation. Help us further improve our SDKs by providing your valuable feedback, reporting issues, and contributions to our codebase.
Firebase is a great platform for developing rich mobile and web applications by leveraging the power and scale of the Google Cloud Platform. Firebase provides a wide range of composable backend services and SDKs that help developers overcome numerous challenges in app development including user authentication, data storage, notification delivery, and more.
In addition to the services and the SDKs, Firebase also offers security rules -- a powerful mechanism that helps enforce the security and logical correctness of your apps. The backend services use security rules to authorize and validate the requests made by client apps, and make sure they adhere to the policies that app developers have put in place. Today, you can use security rules to govern how your users interact with the Firebase Realtime Database, Cloud Storage, and Cloud Firestore. Rules in these Firebase products help you achieve two critical goals:
If you're using any Firebase product mentioned above, rules are essential. But you may have questions about how they fit into your application architecture. In order to shed some light on this subject, we'd like to share a few tips related to security rules and the Admin SDK.
As you explore security rules in depth, you will eventually discover that requests from the Firebase Admin SDK are not gated by rules. The Admin SDK is initialized with a service account, which gives the SDK full access to your data. In Firebase Realtime Database, you can scope the Admin SDK's privileges to a user ID, and enforce rules as usual. But other products, most notably Google Cloud Firestore, don't support this feature yet. You should be mindful about that when implementing server-side data access operations.
Because of the elevated privileges of service accounts and the Admin SDK, you should also make sure that they only get deployed in environments that you trust with administrative control of your project. Typical environments include servers controlled by the developers, and managed cloud environments like Google Cloud Functions and App Engine. On the other hand, end-user devices and web browsers where the application code is open for modification are inherently untrusted, and the Admin SDK should never be deployed in them.
Many applications have data that is critical to the operation of the app, but should never be modified by the users. Consider a forum app that promotes user engagement by awarding its participants points (think StackOverflow). Each forum post needs to be scored in near real-time so the users can track their progress, but the users themselves should never be able to change anyone's points, not even their own.
The simplest way to protect such application-managed data is to specify a rule that prevents all writes to the data from the users.
service cloud.firestore { match /databases/{database}/documents { function isAuthorized() { // Some function that grants users read access. } match /scores/{uid}/{document} { allow write: if false; // Nothing gets past me (except Admin of course). allow read: if isAuthorized(); // Grant read access as necessary. } } }
Then you can use the Admin SDK to implement backend services that keep the data up-to-date. For instance, you can implement a serverless function using Cloud Functions for Firebase that automatically executes whenever a user posts something in the forum. This function can determine how many points to award the user, and update the respective entries in the read-only scores collection.
scores
import * as admin from 'firebase-admin'; admin.initializeApp(); export const updateScores = functions.firestore.document('posts/{userId}/{postId}') .onCreate((snapshot, context) => { const score = calculateScore(snapshot); const userId = context.params.userId; const doc = admin.firestore().collection('scores').document(userId); return admin.firestore().runTransaction((txn) => { return txn.get(doc).then((snap) => { const current = snap.data().total || 0; txn.set(doc, {total: current + score}, {merge: true}); }); }); });
Since Cloud Functions is a trusted environment, the backend code can continue to update your data, while keeping users from doing something they are not allowed to.
Many applications need to deal with users in different roles. What individual users can do in the app usually depends on their roles. Let's take a MOOC (Massively Open Online Courses) app as an example, where there are teachers, students and TAs. Teachers and TAs should be able to view and update course content, but students should only be able to view the material.
In a Firebase app, user roles can be managed by setting custom claims on user accounts. This is a privileged operation that can only be performed in a backend environment, typically using the Admin SDK. Custom claims are additional information that we associate with user accounts in Firebase Auth, and this information becomes available in the ID tokens that Firebase issues to users upon sign in. You can inspect these claims via security rules to facilitate role-based access control.
Going back to our example MOOC app, we can use the following backed code to grant a user teacher role.
import * as admin from 'firebase-admin'; admin.initializeApp(); async function grantTeacherRole(userId: string) { await admin.auth().setCustomUserClaims(userId, {role: 'teacher'}); }
Now you can define a rule that only allows teachers and TAs write-access to the courses collection.
courses
service cloud.firestore { match /databases/{database}/documents { function isTeacher() { return request.auth.token.role == "teacher"; } function isTA() { return request.auth.token.role == "ta"; } match /courses/{doc} { allow write: if isTeacher() || isTA(); // Only teachers and TAs can write. allow read: if true; // But anybody can read. } } }
Note that Firebase client SDKs cache ID tokens up to an hour. Therefore changes to a user's custom claims may take up to an hour to take effect.
Sometimes you want the ability to withhold some data from users until an administrator or a backend service determines it's time to release the data. For example, consider an automated process that grades tests in a MOOC app. You would want this process to finish grading all the tests before any scores are shared with the students. In this case the grading process should be able to update any Firestore document, and it can be deployed in a trusted backend environment. Therefore you can use the Admin SDK to implement it.
To make sure the intermediate states of data are not visible to users, you can create each document with a visibility attribute set to "private". Then in security rules, restrict access to only those documents whose visibility attribute is set to "public". Here's what this rule would look like:
visibility
"private"
"public"
service cloud.firestore { match /databases/{database}/documents { function isPublic() { return resource.data.visibility == "public"; } match /grades/{document} { allow read: if isPublic(); // Cannot read unless marked as "public". allow write: if false; // Nobody except Admin can update the documents. } } }
With the above rules configuration in place, all documents created with the visibility attribute set to "private" are inaccessible to the end-users. When the backend process is ready to release a document to the users, it can use the Admin SDK to change the visibility attribute of the target document to "public".
import * as admin from 'firebase-admin'; admin.initializeApp(); async function gradeTests() { // Create a new document and continue to write to it. const doc = await createNewDoc(); await updateGrades(doc); // Later, make the document visible when ready. await releaseGrades(doc); } async function createNewDoc() { const doc = admin.firestore().collection('grades').document(); // Make the new doc hidden by default await doc.set({visibility: 'private'}); return doc; } async function releaseGrades(doc) { await doc.update({visibility: 'public'}); }
As soon as the visibility attribute is set to "public" on a document, it will start appearing in matching Firestore queries executed by users.
It can be tempting to write rules that apply across collections -- for example, writing a rule that grants teachers in the MOOC app access to all documents in the database. In such situations, remember that rules will grant access to a document if any match statement in the rules configuration grants access. When multiple rules apply to the same document, it is easy to forget that any rule that allows access, overrides all the other rules that deny access.
service cloud.firestore { match /databases/{database}/documents { match /reports/{document} { // This rule is intended to selectively grant users read-only access to the // documents in the 'reports' collection. But the rule below inadvertently // grants teachers read-write access to these documents. allow read: if isConditionMet(); allow write: if false; } match /{document=**} { // This rule matches all documents in the database, including the 'reports' // collection. In case of teachers, this will override the previous rule. allow read, write: if isTeacher(); } } }
To avoid accidentally granting users access to protected data in your app, you should try to write rules in a manner so that each document only matches a single rules statement. One way to make that easier is to avoid wildcards that match collections ({document=**}), and only use wildcards that match documents ({document}). If you're tempted to define overarching rules, consider if the Admin SDK would be a better fit, because as we learned in the Tip #1, requests from the Admin SDK bypasses security rules.
{document=**}
{document}
As your apps grow and evolve over time, you may implement various administrative tools to manage your app's data. For example, you may want to implement a tool that backs up certain Firestore collections or RTDB paths. Or you are trying to meet specific privacy requirements, and you want to implement a service that deletes user data when the data becomes obsolete or when the users demand it. Such tools typically require unrestricted access to large portions of your database.
At first this may look like a good reason to have a relaxed set of security rules. But you should strive to write the most detailed and restrictive rules that describe the access patterns of your app. Administrative tools should be implemented using the Admin SDK, and deployed in a privileged environment that you control. This way your admin tools can retain full access to all the data, while closely regulating what end-users can do in the app.
In some situations you may want to temporarily deny a user access to data. Perhaps the monitoring infrastructure of your forum app has just detected a user posting spam, and you want to prevent that user from posting any more content until you can conduct a thorough investigation of the incident. You can use security rules to implement a simple access control list (ACL) on top of Firestore, and use the Admin SDK to dynamically manage it. You would start by declaring a rule like the following:
service cloud.firestore { match /databases/{database}/documents { function isBlackListed() { return exists(/databases/$(database)/documents/blacklist/$(request.auth.uid)) } // Collections are closed for reads and writes by default. This match block // is included for clarity. match /blacklist/{entry} { allow read: if false; allow write: if false; } match /posts/{postId} { allow write: if !isBlackListed() } } }
This mentions a Firestore collection named blacklist that no user can read or write. It also uses the exists built-in function to check if a document with a given key exists in the Firestore database. If you haven't seen this pattern before, built-in functions like exists and get enable us to access Firestore documents from security rules. In this case, if we find a user ID in the blacklist collection, we prevent the corresponding user from writing to the posts collection. Now we can use the Admin SDK to add users to the blacklist collection, and revoke their write-access:
blacklist
exists
get
posts
await revokeWriteAccess('bAdAgEnT'); async function revokeWriteAccess(userId) { const user = admin.firestore().collection('blacklist').document(userId) await user.set({ reason: 'possible bad agent', blacklisted_at: admin.firestore.FieldValue.serverTimestamp(), }); }
Since you have already locked down all access to the blacklist collection, you can rest assured that only the Admin SDK (i.e. our backend code) can make modifications to it. Changes to the ACL take effect immediately. To grant a user access to the data again, simply remove the corresponding document with the user ID from the blacklist collection.
Note that we are also writing the current timestamp to the same document when adding a user to the blacklist. If you want, you can write a rule that references this property to automatically grant blacklisted users access after a cool off period.
service cloud.firestore { function isTwoDaysElapsed() { return request.time > timestamp.value(get(/databases/$(database)/documents/ blacklist/$(request.auth.uid)).data.blacklisted_at.seconds*1000) + duration.value(2, 'd'); } match /databases/{database}/documents { match /posts/{postId} { // allow if blacklisted more than 2 days ago allow write: if isTwoDaysElapsed(); } } }
Firebase takes a declarative approach to ensuring the security and logical correctness of your apps. By keeping the rules separate from application code, you can easily update your security policies, while keeping the application code simple. As many developers know by experience, code changes are harder to make, and even harder to test and deploy. But with Firebase, you can rapidly iterate on your rules without having to touch the application code at all. Moreover, you can patch any detected security vulnerabilities instantly, without having to go through a long and arduous app rollout.
You can also use rules in conjunction with the Firebase Admin SDK to implement sophisticated use cases that involve server-side code. Admin SDK is not subjected to rules checks, but this extra degree of freedom enables some useful patterns that can be applied to multiple real world applications. You can implement any server-side components using the Admin SDK and deploy them in trusted environments like Google Cloud Functions, while subjecting the client-side apps to stricter constraints.
Read more about Firebase security rules and the Admin SDK in our documentation. If you have used these tools to solve any interesting problems, we'd love to hear about your experience. Happy coding with Firebase!
I'm always amazed when I think about the fact that Firebase Cloud Messaging sends billions of messages a day. Developers on iOS, Android, and web rely on FCM to send notifications and data messages to their clients. We recently updated FCM to incorporate better security and new features, and now you can access the new FCM through the Firebase Admin SDK for Node.js, Python, Java, and Go.
The latest version of FCM, called FCM v1, includes the ability to send a single request with platform-specific overrides. For example, you can set a time to live for an Android notification and an APNs priority for an iOS notification in the same body. See the documentation or this blog post for more information on platform overrides.
You can now conveniently integrate your server-side applications with the FCM v1 API using the Firebase Admin SDKs. Here's how you can send a simple data message in Node.js:
var registrationToken = 'YOUR_REGISTRATION_TOKEN'; var message = { data: { score: '850', time: '2:45' }, token: registrationToken }; admin.messaging().send(message) .then((response) => { console.log('Successfully sent message:', response); }) .catch((error) => { console.log('Error sending message:', error); });
To see this code in Java, Python, and Go, check the documentation. To see all message payload options, check out the FCM v1 documentation. In addition to sending messages to devices and topics, the Admin SDK for FCM also allows you to manage topic subscriptions from your server.
Here's an example of subscribing to a topic in Node.js:
var registrationTokens = [ 'YOUR_REGISTRATION_TOKEN_1', // ... 'YOUR_REGISTRATION_TOKEN_n' ]; admin.messaging().subscribeToTopic(registrationTokens, topic) .then(function(response) { console.log('Successfully subscribed to topic:', response); }) .catch(function(error) { console.log('Error subscribing to topic:', error); });
To see this code in Java, Python, and Go, check the documentation. Thanks to the Admin SDK, it's even easier than ever to send messages! Check out the full documentation here. And if you build something cool with FCM, be sure to tell us about it! Tweet @Firebase and @ThatJenPerson and let us know how it's going!
The Firebase Admin SDK for Go is now generally available. This is the fourth programming language to join our growing family of Admin SDKs, which already includes support for Java, Python and Node.js. Firebase Admin SDKs enable application developers to programmatically access Firebase services from trusted environments. They complement the Firebase client SDKs, which enable end users to access Firebase from their web browsers and mobile devices. The initial release of the Firebase Admin SDK for Go comes with some Firebase Authentication features: custom token minting and ID token verification.
Similar to the other Firebase Admin SDKs, the Go Admin SDK can be initialized with a variety of authentication credentials and client options. The following code snippet shows how to initialize the SDK using a service account credential obtained from the Firebase console or the Google Cloud console:
import ( "golang.org/x/net/context" firebase "firebase.google.com/go" "google.golang.org/api/option" ) opt := option.WithCredentialsFile("path/to/key.json") app, err := firebase.NewApp(context.Background(), nil, opt)
If you are running your code on Google infrastructure, such as Google App Engine or Google Compute Engine, the SDK can auto-discover application default credentials from the environment. In this case you do not have to explicitly specify any credentials when initializing the Go Admin SDK:
import ( "golang.org/x/net/context" firebase "firebase.google.com/go" ) app, err := firebase.NewApp(context.Background(), nil)
The initial release of the Firebase Admin SDK for Go comes with support for minting custom tokens and verifying Firebase ID tokens. The custom token minting allows you to authenticate users using your own user store or authentication mechanism:
client, err := app.Auth() if err != nil { return err } claims := map[string]interface{}{ "premium": true, "package": "gold", } token, err := client.CustomToken("some-uid", claims)
The resulting custom token can be sent to a client device, where it can be used to initiate an authentication flow using a Firebase client SDK. On the other hand, the ID token verification facilitates securely identifying the currently signed in user on your server:
client, err := app.Auth() if err != nil { return err } decoded, err := client.VerifyIDToken(idToken) uid := decoded.UID
To learn more about using the Firebase Admin SDK for Go, see our Admin SDK setup guide.
We plan to further expand the capabilities of the Go Admin SDK by implementing other useful APIs such as user management and Firebase Cloud Messaging. This SDK is also open source. Therefore we welcome you to browse our Github repo and get involved in the development process by reporting issues and sending pull requests. To all Golang gophers out there, happy coding with Firebase!
Last April, we announced the general availability of the Firebase Admin SDK for Python. The initial release of this SDK supported two important features related to Firebase Authentication: minting custom tokens, and verifying ID tokens. Now, we are excited to announce that database support is available in the Firebase Admin SDK for Python starting from version 2.1.0.
Due to the way it's implemented, there are several notable differences between this API and the database APIs found in our other Admin SDKs (Node.js and Java). The most prominent of these differences is the lack of support for realtime event listeners. The Python Admin SDK currently does not provide a way to add event listeners to a database reference in order to receive realtime update notifications. Instead, all data retrieval operations are provided as blocking methods. However, despite these differences there's a lot that can be achieved using this API.
The database module of the Python Admin SDK facilitates both basic data manipulation operations and advanced queries. To begin interacting with the database from a Python environment, initialize the SDK with the Realtime Database URL:
import firebase_admin from firebase_admin import credentials cred = credentials.Cert('path/to/serviceKey.json') firebase_admin.initialize_app(cred, { 'databaseURL' : 'https://my-db.firebaseio.com' })
Then obtain a database reference from the db module of the SDK. Database references expose common database operations as Python methods (get(), set(), push(), update() and delete()):
db
get(), set(), push(), update()
delete()
from firebase_admin import db root = db.reference() # Add a new user under /users. new_user = root.child('users').push({ 'name' : 'Mary Anning', 'since' : 1700 }) # Update a child attribute of the new user. new_user.update({'since' : 1799}) # Obtain a new reference to the user, and retrieve child data. # Result will be made available as a Python dict. mary = db.reference('users/{0}'.format(new_user.key)).get() print 'Name:', mary['name'] print 'Since:', mary['since']
In the Firebase Realtime Database, all data values are stored as JSON. Note how the Python Admin SDK seamlessly converts between JSON and Python's native data types.
To execute an advanced query, call one of the order_by_* methods available on the database reference. This returns a query object, which can be used to specify additional parameters. You can use this API to execute limit queries and range queries against your data, and retrieve sorted results.
order_by_*
from firebase_admin import db dinos = db.reference('dinosaurs') # Retrieve the five tallest dinosaurs in the database sorted by height. # 'result' will be a sorted data structure (list or OrderedDict). result = dinos.order_by_child('height').limit_to_last(5).get() # Retrieve the 5 shortest dinosaurs that are taller than 2m. result = dinos.order_by_child('height').start_at(2).limit_to_first(5).get() # Retrieve the score entries whose values are between 50 and 60. result = db.reference('scores').order_by_value() \ .start_at(50).end_at(60).get()
Take a look at the Admin SDK documentation for more information about this new API. Also check out our Github repo, and help us further improve the Admin SDK by reporting issues and contributing patches. In fact, it was your continuing feedback that motivated us to build and release this API in such a short period. Happy coding with Firebase!
As the developer or the administrator of an app built on Firebase, you may need to perform various user management tasks. These include:
The Firebase Admin SDK provides a powerful API for performing these kinds of user management tasks from privileged environments. Using the Admin SDK, you can program these capabilities directly into your admin consoles, dashboards and other backend services. Unlike the Firebase client SDK, the Admin SDK is initialized with a service account credential, which grants the SDK elevated privileges necessary to perform user management operations.
This is not a brand new feature. The Firebase Admin Node.js SDK has had a user management API for a while. However, we are happy to announce that this API is now also available in our Admin Java SDK starting from version 5.1.0. This is one of the most requested features for the Admin Java SDK, and we are certain many Firebase app developers are going to find it useful.
The Java user management API closely mirrors its Node.js counterpart. Specifically, it consists of five new methods:
getUser()
getUserByEmail()
createUser()
updateUser()
deleteUser()
Following code snippet shows how to use some of these new methods in practice. In this example we retrieve an existing user account, and update some of its attributes:
final FirebaseAuth auth = FirebaseAuth.getInstance(); Task task = auth.getUserByEmail("editor@example.com") .addOnSuccessListener(userRecord -> { System.out.println("Successfully fetched user data: " + userRecord.getUid()); UpdateRequest update = userRecord.updateRequest() .setDisabled(false) // Enable the user account .setEmailVerified(true); // Set the email verification status auth.updateUser(update); }) .addOnFailureListener(e -> { System.err.println("Error fetching user data: " + e.getMessage()); });
You can learn more about the Firebase user management API from the Admin SDK documentation. Additionally, head over to our Github repo to see how it is implemented. (Yes, it's all open source!). You can also help us further improve this API by providing us feedback and reporting issues. As always, we are open to all sorts of contributions including pull requests to our codebase. Happy coding with Firebase!
We are pleased to announce that we are taking our first steps towards open sourcing our client libraries. By making our SDKs open, we're aiming to show our commitment to greater transparency and to building a stronger developer community. To help further that goal, we'll be using GitHub as a core part of our own toolchain to enable all of you to contribute as well. As you find issues in our code, from inconsistent style to bugs, you can file issues through the standard GitHub issue tracker. You can also find our project in the Google Open Source directory. We're really looking forward to your pull requests!
We're starting by open sourcing several products in our iOS, JavaScript, Java, Node.js and Python SDKs. We'll be looking at open sourcing our Android SDK as well. The SDKs are being licensed under Apache 2.0, the same flexible license as existing Firebase open source projects like FirebaseUI.
Let's take a look at each repo:
https://github.com/firebase/firebase-ios-sdk
With the launch of the Firebase iOS 4.0 SDKs we have made several improvements to the developer experience, such as more idiomatic API names for our Swift users. By open sourcing our iOS SDKs we hope to provide an additional avenue for you to give us feedback on such features. For this first release we are open sourcing our Realtime Database, Auth, Cloud Storage and Cloud Messaging (FCM) SDKs, but going forward we intend to release more.
Because we aren't yet able to open source some of the Firebase components, the full product build process isn't available. While you can use this repo to build a FirebaseDev pod, our libraries distributed through CocoaPods will continue to be static frameworks for the time being. We are continually looking for ways to improve the developer experience for developers, however you integrate.
Our GitHub README provides more details on how you build, test and contribute to our iOS SDKs.
https://github.com/firebase/firebase-js-sdk
We are excited to announce that we are open sourcing our Realtime Database, Cloud Storage and Cloud Messaging (FCM) SDKs for JavaScript. We'll have a couple of improvements hot on the heels of this initial release, including open sourcing Firebase Authentication. We are also in the process of releasing the source maps for our components, which we expect would really improve the debuggability of your app.
Our GitHub repo includes instructions on how you can build, test and contribute.
Node.js: https://github.com/firebase/firebase-admin-node
Java: https://github.com/firebase/firebase-admin-java
Python: https://github.com/firebase/firebase-admin-python
We are happy to announce that all three of our Admin SDKs for accessing Firebase on privileged environments are now fully open source, including our recently-launched Python SDK. While we continue to explore supporting more languages, we encourage you to use our source as inspiration to enable Firebase for your environment. (And if you do, we'd love to hear about it!)
We're really excited to see what you do with the updated SDKs - as always reach out to us with feedback or questions in the Firebase-Talk Google Group, on Stack Overflow, via the Firebase Support team, or now on GitHub for SDK issues and pull requests! And to read about the other improvements to Firebase that launched at Google I/O, head over to the Firebase blog.
import firebase_admin from firebase_admin import credentials cred = credentials.Certificate("path/to/service.json") firebase_admin.initialize_app(cred)
firebase_admin.initialize_app()
uid = "some-uid" additional_claims = { "premiumAccount": True } custom_token = auth.create_custom_token(uid, additional_claims)
decoded_token = auth.verify_id_token(id_token) uid = decoded_token["uid"]
/topics/falcons
/topics/patriots
var admin = require("firebase-admin"); // Fetch the service account key JSON file contents var serviceAccount = require("path/to/serviceAccountKey.json"); // Initialize the app with a service account, granting admin privileges admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://<DATABASE_NAME>.firebaseio.com" }); // Define who to send the message to var condition = "'falcons' in topics || 'patriots' in topics"; // Define the message payload var payload = { notification: { title: "Super Bowl LI: Falcons vs. Patriots", body: "Your team is Super Bowl bound! Get the inside scoop on the big game." } }; // Send a message to the condition with the provided payload admin.messaging.sendToCondition(condition, payload) .then(function(response) { console.log("Successfully sent message! Server response:", response); }) .catch(function(error) { console.log("Error sending message:", error); });
// condition and payload are the same as above var options = { priority: "high", timeToLive: 60 * 60 * 24 * 7 }; admin.messaging.sendToCondition(condition, payload, options) .then(function(response) { console.log("Successfully sent message! Server response:", response); }) .catch(function(error) { console.log("Error sending message:", error); });
setServiceAccount()
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountCredentials.json"); FirebaseOptions options = new FirebaseOptions.Builder() .setServiceAccount(serviceAccount) .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com") .build(); FirebaseApp.initializeApp(options);
setCredential()
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountCredentials.json"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.fromCertificate(serviceAccount)) .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com") .build(); FirebaseApp.initializeApp(options);
FirebaseOptions options = new FirebaseOptions.Builder() .setCredential(FirebaseCredentials.applicationDefault()) .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com") .build(); FirebaseApp.initializeApp(options);
With Firebase, we've been working towards a world where developers don't have to deal with managing servers and can instead build web and mobile apps with only client-side code. However, there are times when you really do need to spin up your own server. For example, you may want to integrate with a third-party API (such as an email or SMS service), complete a computationally expensive task, or have a need for a trusted actor. We want to make your experience on this part of your stack as simple as it is on the front-end. Towards that aim, we announced the Firebase Admin SDKs for Node.js and Java at the Firebase Dev Summit in Berlin earlier this week.
What are the Admin SDKs?
The Firebase Admin SDKs provide developers with programmatic, second-party access to Firebase services from server environments. Second-party here refers to the fact that the SDKs are granted elevated permissions that allow them to do more than a normal, untrusted client device can. The Admin SDKs get these elevated permissions since they are authenticated with a service account, a special Google account that can be used by applications to access Google services programmatically. The Admin SDKs are meant to complement the existing Firebase web and mobile clients which provide third-party, end-user access to Firebase services on client devices.
Some of this may sound familiar for those of you who have used the existing Firebase Node.js and Java SDKs. The difference is that we have now split the second-party (aka "admin") and third-party (aka "end-user") access use cases into separate SDKs instead of conflating them together. This should make it easier for beginners and experts alike to know which SDK to use and which documentation to follow. It also allows us to tailor the Admin SDKs towards server-specific use cases. A great example of this is the new user management auth API which we will go into in the next section.
What can the Admin SDKs do?
The Admin SDKs for Node.js and Java offer the following admin capabilities that already existed in the prior server SDKs:
In addition, the Node.js SDK brings some exciting new functionality:
How can I get started with the Admin SDKs?
The best place to start is with our Admin SDKs setup guide. The guide will walk you through how to download the SDK, generate a service account key file, and use that key file to initialize the Admin SDK. Thanks to our new Service Accounts panel in your Firebase Console settings, generating service account keys should be a breeze.
What's next for the Admin SDKs?
This is really just the beginning for the Admin SDKs. We plan to expand the Admin SDKs across two dimensions. Firstly, we want to provide Admin SDKs in more programming languages, allowing you to write code in the language you feel most comfortable. Secondly, we plan to integrate with more Firebase services, including adding support for services like Firebase Cloud Messaging and bringing the new user management API to Java.
Would you like us to build an Admin SDK in a particular language? Do you want the Admin SDKs to support a certain Firebase service or feature? Let us know in the comments below or by sending us a note through our feature request support channel.
We are excited to expand our first-class support for backend developers in the Firebase ecosystem. Stay tuned for more to come in the future!