Gathering detailed insights and metrics for @lowfront/firebase-adapter
Gathering detailed insights and metrics for @lowfront/firebase-adapter
Gathering detailed insights and metrics for @lowfront/firebase-adapter
Gathering detailed insights and metrics for @lowfront/firebase-adapter
npm install @lowfront/firebase-adapter
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
4
Firebase can handle the database in the client, but there is not enough providers for authentication provided by Firebase. This package allows you to create rules in Firebase using credentials from various OAuth providers in NextAuth.js, and allows you to use Firebase in the client while the database is protected.
This package is Adapter plug-in for NextAuth.js to use custom token method authentication. Supports both Cloud Firestore and Realtime Database. If you want to get started quickly, see the example below.
This package is compatible with NextAuth.js v4, Firebase-admin v10, and Firebase SDK v9. The NextAuth.js and Firebase Admin SDK must be installed. The Firebase SDK must be installed to use the database on the client.
npm i @lowfront/firebase-adapter
The server uses the Firebase admin SDK. Initialize the app and db as follows:
1// pages/api/auth/[...nextauth].ts
2import { FirestoreAdapter } from "@lowfront/firebase-adapter";
3import admin from 'firebase-admin';
4import { getFirestore } from 'firebase-admin/firestore';
5
6const app = admin.initializeApp({
7 // https://firebase.google.com/docs/admin/setup#initialize-sdk
8 // It is recommended to make it an environment variable to distribute to vercel: https://github.com/lowfront/firebase-adapter/blob/master/example/lib/firebase-server.ts#L9-L18
9 credential: admin.credential.cert({...} as ServiceAccount),
10});
11
12const db = getFirestore(app);
13
14export default NextAuth({
15 providers: [GoogleProvider({ ... })],
16 adapter: FirestoreAdapter(db),
17});
1// pages/api/auth/[...nextauth].ts
2import { FirebaseAdapter } from "@lowfront/firebase-adapter";
3import admin from 'firebase-admin';
4import { getFirestore } from 'firebase-admin/firestore';
5
6const app = admin.initializeApp({
7 // https://firebase.google.com/docs/admin/setup#initialize-sdk
8 // It is recommended to make it an environment variable to distribute to vercel: https://github.com/lowfront/firebase-adapter/blob/master/example/lib/firebase-server.ts#L9-L18
9 credential: admin.credential.cert({...} as ServiceAccount),
10
11 // If you want to use the Realtime Database, add the databaseURL : https://firebase.google.com/docs/admin/setup#initialize-sdk
12 databaseURL: '...',
13});
14
15const db = getDatabase(app);
16export default NextAuth({
17 providers: [GoogleProvider({ ... })],
18 adapter: FirebaseAdapter(db),
19});
Endpoint for requesting the client to issue a cutomToken. You must use /api/auth/firebase-cutom-token
as the endpoint.
1// pages/api/auth/firebase-custom-token.ts 2import { createFirebaseCustomTokenHandler } from "@lowfront/firebase-adapter"; 3 4export default createFirebaseCustomTokenHandler({ 5 db, // Cloud Firestore or Realtime Database Initialized with Firebase admin SDK 6 // additionalClaims: (session) => ({}), // Additional data required by the database rule can be inserted : https://firebase.google.com/docs/auth/admin/create-custom-tokens#sign_in_using_custom_tokens_on_clients 7});
Set a rule in the client that allows users to access only their own data. If you do not set a rule, all data in the database can be accessed by the client, so Firebase database rule must be set up to protect user-specific data. In the example, we used path /store/{userId}/{document=**}
as the user data storage path, but you can change it if you want. Check the official document for more information on the rules.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
match /store/{userId}/{document=**} {
allow read, write: if request.auth.uid == userId
// This line adds a read cost, but disables customToken issued after sign out.
&& exists(/databases/$(database)/documents/_next_auth_firebase_adapter_/store/customToken/$(request.auth.token.sessionToken));
}
}
}
{
"rules": {
".read": false,
".write": false,
// Adds an index to the next-auth data for efficient search.
"_next_auth_firebase_adapter_": {
"account": {
".indexOn": ["providerAccountId"]
},
"session": {
".indexOn": ["sessionToken"]
},
"user": {
".indexOn": ["email"]
},
"verificationToken": {
".indexOn": ["token"]
}
},
// Realtime Database cannot use the email address as a key, so it uses the value encoded in base64 for the email address stored in claims instead of the email address.The operation method is the same as the Firestore rule.
"users": {
"$uid": {
".write": "auth != null && $uid === auth.token.uid && root.child('_next_auth_firebase_adapter_').child('customToken').child(auth.token.sessionToken).exists()",
".read": "auth != null && $uid === auth.token.uid && root.child('_next_auth_firebase_adapter_').child('customToken').child(auth.token.sessionToken).exists()"
}
}
}
}
Unlike servers, the client uses the Firebase SDK to access the database. So, initialize the app with Firebase config and pass the db object to the function provided by the package for use it. The CRUD function (setDoc, addDoc, getDoc, updateDoc, removeDoc...) in Firebase v9 must use the functions wrapped in the package. The wrapper functions have the same signature as Firebase SDK v9.
1import { getUserDoc, getDoc, addDoc, getDoc, getDocs, setDoc, updateDoc, deleteDoc } from '@lowfront/firebase-adapter'; 2 3// It is recommended to make it an environment variable to distribute to vercel: https://github.com/lowfront/firebase-adapter/blob/master/example/lib/firebase-web.ts#L12-L18 4const firebaseConfig = { ... } as FirebaseOptions; 5 6// Initialize Firebase 7const app = initializeApp(firebaseConfig); 8const db = getFirestore(app); 9 10const testDoc = getUserDoc(db, session?.user?.email, 'store', 'test'); 11 12const App: FC<{}> = () => { 13 const { data: session } = useSession(); 14 15 const loadData = async () => { 16 await getDoc(testDoc); 17 alert('success load data'); 18 }; 19 20 return <div> 21 <button onClick={loadData}>Load data</button> 22 </div> 23};
The current Realtime Database should wrap requests with a login check function instead of a wrapper function. See the example code for more information.
1import { signInFirebase, trySignInWithCustomToken } from '@lowfront/firebase-adapter/web'; 2import { get, ref } from 'firebase/database'; 3 4async function loadData() { 5 console.log(`users/${btoa(session?.user?.email ?? '')}`); 6 try { 7 await trySignInWithCustomToken(() => get(ref(db, `users/${btoa(session?.user?.email ?? '')}`)), getApp()); // The Realtime Database uses the value encoded as base64 as the user storage path because email is not available as a key. 8 alert('success load data'); 9 } catch (err) { 10 console.log(err); 11 alert('Fail load data'); 12 } 13}
No vulnerabilities found.
No security vulnerabilities found.