Skip to main content

Firebase Authentication

Integrate Firebase Authentication with Squid to manage access to Squid resources through the Squid Client and Backend SDKs.

To use Firebase Authentication with Squid, first add the Firebase Authentication integration in the Squid Console. To learn how to set up the integration, view the Firebase Authentication setup guide.

Install the react-firebase-hooks and firebase packages:

npm install --save firebase react-firebase-hooks
Note

The react-firebase-hooks is a third-party package that is not maintained by Firebase. You can opt not to use this package, but you will have to write and maintain your own code to handle observability to keep your auth token up-to-date.

Initialize Firebase

Create a firebase configuration file called firebase.ts in the src directory. Provide the following information:

Client code
// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

// TODO: Add SDKs for other Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration

const firebaseConfig = {
apiKey: 'YOUR_FIREBASE_API-KEY',
authDomain: 'YOUR_FIREBASE_PROJECT_ID.firebaseapp.com',
projectId: 'YOUR_FIREBASE_PROJECT_ID',
appId: 'YOUR_FIREBASE_APP_ID',
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);
export default firebaseApp;

Set the user's auth ID token

The following code gets the Firebase Authentication token from Firebase and passes it to the Squid backend. From there, you can access the auth context to manage access to data and APIs.

Client code
import { useState, useEffect } from 'react';
import { useSquid } from '@squidcloud/react';
import { useIdToken } from 'react-firebase-hooks/auth';
import { auth } from './firebase.ts';
import './App.css';


function App() {
// Get Firebase Authentication state
const [user, loading, error] = useIdToken(auth);
const { setAuthProvider } = useSquid();

useEffect(() => {
// Pass the auth token to the Squid backend
setAuthProvider({
integrationId: 'YOUR_FIREBASE_AUTH_INTEGRATION_ID',
getToken: async () => {
if (!user) return undefined;
return await user.getIdToken();
},
});
if (loading) return;
if (!user) {
// Change the view as needed for when a user is logged out.
} else {
// Change the view as needed for when a user is logged in.
}
}, [user, loading, setAuthProvider]);

The following is an example of how to access the authentication information on the backend:

Backend code
@secureCollection('users', 'read')
secureUsersRead(context: QueryContext<User>): boolean {
const userAuth = this.getUserAuth();
... // Take action with auth information
}

To learn more about securing data in the Squid backend, view the documentation on security rules.