npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kaayan/firebase-auth-sdk

v1.1.2

Published

Reusable Firebase Auth SDK in TypeScript

Readme

npm version

Firebase Authentication SDK

A type-safe, UI-free Firebase Authentication SDK that provides a clean and easy-to-use API for authenticating users in web applications.

Features

  • 🔐 Complete Firebase Authentication flow
  • 🛠️ No UI components - bring your own UI
  • 📦 Multiple auth providers (Google, Facebook, Apple, GitHub, Email/Password)
  • 🔒 Secure token management for server-side validation
  • 📱 Framework agnostic - works with any frontend library/framework

Installation

npm install @kaayan/firebase-auth-sdk
# or
yarn add @kaayan/firebase-auth-sdk

Basic Usage

import { createAuthSDK } from '@kaayan/firebase-auth-sdk';

// Initialize the SDK
const auth = createAuthSDK({
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,  //  your-api-key
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,  // your-app.firebaseapp.com
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,   // your-project-id
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,   // your-storage-bucket
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,  // your-app-id
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID   // your-appId
  enabledProviders: {
    google: true,
    facebook: true,
    apple: true,
    github: true
  }
});

// Use authentication methods
auth.signInWithGoogle()
  .then(userCredential => console.log('Signed in!', userCredential))
  .catch(error => console.error('Error signing in', error));

Secure Authentication in Production

This SDK provides tools for implementing secure authentication in production environments.

Getting Authentication Tokens

// Get the authenticated user with ID token
const result = await auth.getAuthenticatedUser();

if (result.success && result.data) {
  const { token, uid, email } = result.data;
  
  // Use token for authenticated API requests
  // DO NOT store this token in localStorage or sessionStorage
} else {
  // Handle authentication error
  console.error(result.error?.message);
}

Force Refreshing Tokens

Tokens expire after 1 hour. You can force refresh:

// Force refresh token
const result = await auth.getAuthenticatedUser(true);

Setting Up HttpOnly Cookies (Client-Side)

After authenticating, send the token to your backend to set secure HttpOnly cookies:

async function handleLogin() {
  const result = await auth.signInWithGoogle();
  
  if (result) {
    // Get fresh token
    const authResult = await auth.getAuthenticatedUser();
    
    if (authResult.success && authResult.data) {
      // Send token to your server to create HttpOnly cookie
      await fetch('/api/auth/session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token: authResult.data.token }),
        credentials: 'include' // Important for cookies
      });
      
      // Redirect or update UI
    }
  }
}

Server-Side Token Validation (Next.js Example)

In your Next.js API route or middleware:

// pages/api/auth/session.js
import { getAuth } from 'firebase-admin/auth';
import { initializeApp, cert } from 'firebase-admin/app';

// Initialize Firebase Admin SDK
if (!global.firebaseAdmin) {
  global.firebaseAdmin = initializeApp({
    credential: cert({
      projectId: process.env.FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
    }),
  });
}

export default async function handler(req, res) {
  try {
    // Get token from request body
    const { token } = req.body;
    
    // Verify ID token
    const decodedToken = await getAuth().verifyIdToken(token);
    
    // Set HttpOnly cookie with session info
    res.setHeader('Set-Cookie', [
      `session=${token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${60 * 60}`
    ]);
    
    res.status(200).json({ success: true });
  } catch (error) {
    console.error('Error setting session', error);
    res.status(401).json({ error: 'Unauthorized' });
  }
}

SSR Authentication with Middleware (Next.js Example)

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getAuth } from 'firebase-admin/auth';

export async function middleware(req: NextRequest) {
  const session = req.cookies.get('session')?.value || '';
  
  // Validate session
  if (!session) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
  
  try {
    // Verify session token with Firebase Admin
    const decodedToken = await getAuth().verifyIdToken(session);
    
    // Token is valid, proceed with request
    return NextResponse.next();
  } catch (error) {
    // Invalid session, redirect to login
    return NextResponse.redirect(new URL('/login', req.url));
  }
}

// Add protected routes
export const config = {
  matcher: ['/protected/:path*', '/dashboard/:path*'],
};

Security Best Practices

  1. Never store tokens in localStorage or sessionStorage

    • These can be accessed by any JavaScript running on your domain, including XSS attacks
  2. Always use HttpOnly cookies for storing authentication tokens

    • Set Secure flag in production
    • Set SameSite=Strict to prevent CSRF attacks
  3. Implement proper CSRF protection

    • For mutations/sensitive actions, use CSRF tokens
  4. Regularly refresh tokens

    • Firebase ID tokens expire after 1 hour
    • Implement refresh logic for long-lasting sessions

🛡 Licensed under MIT • Maintained by alireza ibrahimi 📫 Questions? Email [email protected] or open an issue on GitHub