0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Custom Token Authentication in Firebase

To use custom token authentication in Firebase, first create a custom token on your backend using the Firebase Admin SDK, then sign in the user on the client with signInWithCustomToken(). This lets you authenticate users with your own system while leveraging Firebase services.
📐

Syntax

Custom token authentication involves two main steps:

  • Create a custom token on your backend using Firebase Admin SDK.
  • Sign in with the custom token on the client using Firebase Authentication SDK.

The backend code generates a token with user info, and the client uses that token to authenticate.

javascript
// Backend: Create custom token
const admin = require('firebase-admin');
admin.initializeApp({
  credential: admin.credential.applicationDefault()
});

const uid = 'some-unique-user-id';
admin.auth().createCustomToken(uid)
  .then((customToken) => {
    // Send token to client
    console.log(customToken);
  })
  .catch((error) => {
    console.error('Error creating custom token:', error);
  });

// Client: Sign in with custom token
import { getAuth, signInWithCustomToken } from 'firebase/auth';

const auth = getAuth();
signInWithCustomToken(auth, customToken)
  .then((userCredential) => {
    console.log('User signed in:', userCredential.user.uid);
  })
  .catch((error) => {
    console.error('Sign-in error:', error);
  });
💻

Example

This example shows how to create a custom token on a Node.js backend and then sign in on a web client using that token.

javascript
// Backend (Node.js)
const admin = require('firebase-admin');
admin.initializeApp({
  credential: admin.credential.applicationDefault()
});

async function createToken() {
  const uid = 'user123';
  try {
    const token = await admin.auth().createCustomToken(uid);
    console.log('Custom Token:', token);
    return token;
  } catch (error) {
    console.error('Error creating token:', error);
  }
}

createToken();

// Client (JavaScript)
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithCustomToken } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID'
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// Assume customToken is received from backend
const customToken = 'RECEIVED_CUSTOM_TOKEN';

signInWithCustomToken(auth, customToken)
  .then((userCredential) => {
    console.log('Signed in user ID:', userCredential.user.uid);
  })
  .catch((error) => {
    console.error('Sign-in failed:', error);
  });
Output
Custom Token: eyJhbGciOiJSUzI1NiIsImtpZCI6Ij... (token string) Signed in user ID: user123
⚠️

Common Pitfalls

  • Not initializing Firebase Admin SDK properly: Make sure your backend has correct credentials and initialization.
  • Using expired or malformed tokens: Tokens must be freshly generated and valid.
  • Not sending the token securely to the client: Use HTTPS and secure channels.
  • Trying to sign in on client before receiving token: Wait for the token from backend before calling signInWithCustomToken().
javascript
// Wrong: Using a hardcoded or expired token
const expiredToken = 'old_token_string';
signInWithCustomToken(auth, expiredToken)
  .catch(error => console.error('Error:', error));

// Right: Generate fresh token on backend and use it
// See example section for correct usage
📊

Quick Reference

StepDescription
Create custom tokenUse Firebase Admin SDK on backend with user ID
Send token to clientSecurely deliver the token to your app
Sign in clientCall signInWithCustomToken() with the token
Use Firebase servicesAccess Firebase features as authenticated user

Key Takeaways

Generate custom tokens on your backend using Firebase Admin SDK with a unique user ID.
Use signInWithCustomToken() on the client to authenticate users with the custom token.
Ensure tokens are fresh, valid, and securely transmitted to avoid authentication errors.
Initialize Firebase Admin SDK correctly with proper credentials on your backend.
Wait for the custom token from backend before attempting client sign-in.