This plugin adds the Firebase Admin SDK to Fastify so you can easy use Firebase Auth, Firestore, Cloud Storage, Cloud Messaging, and more.
yarn add @now-ims/fastify-firebase
npm i @now-ims/fastify-firebase -S
Add it to you project with register
and you're done!
This plugin will add a firebase
namespace in your Fastify instance - you can access the Firebase SDK objects via fastify.firebase
:
auth - e.g., fastify.firebase.auth().createUser()
firestore - e.g., fastify.firebase.firestore().collection('users').get()
storage - e.g., fastify.firebase.store().bucket('thumbnails')
machineLearning - e.g., fastify.firebase.machineLearning().createModel()
options
- if deploying from Google Cloud options are optionalname
(Default:'default'
, Type:string
) is required if you want to load configurations for multiple projectscert
(Optional, Type:string
) is required if you you are not on Google Cloud or want to load multiple configurationsdatabaseURL
(Optional, Type:string
) is required for Realtime DatabasestorageBucket
(Optional, Type:string
) e.g.,<BUCKET_NAME>.appspot.com
- do not include anygs://
projectId
(Default:'cert.projectId'
, Type:string
) e.g.,my-google-cloud-project
const fastify = require('fastify')({ logger: true });
fastify.register(require('fastify-sensible'));
fastify.register(require('@now-ims/fastify-firebase'));
fastify.get('/user/:id', async (req, reply) => {
const user = await fastify.firebase
.firestore()
.collection('users')
.doc(req.params.id)
.get();
if (!user.exists) {
return reply.notFound();
}
return user.data();
});
fastify.listen(4331, (err) => {
if (err) throw err;
console.log(`server listening on ${fastify.server.address().port}`);
});
const fastify = require('fastify')({ logger: true });
fastify.register(require('fastify-sensible'));
// Here we will load multiple configurations for multiple projects!
// You most likely will not need this, but it is available should you need it.
fastify.register(require('@now-ims/fastify-firebase'), {
name: 'client1',
cert: '/path/to/my/cert/',
});
// this can be called with either fastify.firebase or fastify.firebase['client1']
fastify.register(require('@now-ims/fastify-firebase'), {
name: 'client2',
cert: process.env.FIREBASE_CONFIG,
storageBucket: 'thumbnails.appspot.com',
});
// this can only be called with fastify.firebase['client2']
fastify.listen(4331, (err) => {
if (err) throw err;
console.log(`server listening on ${fastify.server.address().port}`);
});
In your route file you can simply do the following e.g.:
async function userRoute(fastify, options) {
fastify.get('/users/:id', async (req, reply) => {
const { id } = req.params;
const user = await fastify.firebase['client2']
.firestore()
.collection('users')
.get(id)
.get();
if (!user.exists) {
return reply.notFound();
}
return user.data();
});
}
This project is sponsored and maintained by:
Licensed under MIT.