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

@loonylabs/react-native-offline-auth

v1.0.1

Published

Offline-first authentication library for React Native with Guest Mode and JWT support

Downloads

5

Readme

@loonylabs/react-native-offline-auth

Offline-first authentication library for React Native with Guest Mode and JWT support

npm version License: MIT TypeScript

A production-ready authentication library for React Native that prioritizes offline-first functionality. Built with TypeScript, Zustand, and AsyncStorage.

Features

  • Offline-First - Works without internet, syncs when available
  • Guest Mode - Let users try your app without registration
  • Easy Upgrade - Seamless guest → authenticated account flow
  • JWT Support - Standard JWT token management
  • Type-Safe - Full TypeScript support with comprehensive types
  • Zero Native Code - Pure JavaScript/TypeScript, works with Expo
  • Flexible API - Bring your own API implementation
  • Tree-Shakeable - Optimized bundle size

Installation

npm install @loonylabs/react-native-offline-auth zustand @react-native-async-storage/async-storage

or

yarn add @loonylabs/react-native-offline-auth zustand @react-native-async-storage/async-storage

Peer Dependencies

This library requires:

  • react >= 18.0.0
  • react-native >= 0.70.0
  • zustand >= 4.0.0
  • @react-native-async-storage/async-storage >= 1.17.0

Quick Start

1. Wrap your app with AuthProvider

import { AuthProvider } from '@loonylabs/react-native-offline-auth';
import App from './App';

export default function Root() {
  return (
    <AuthProvider
      apiCallbacks={{
        login: async (credentials) => {
          const response = await fetch('https://api.example.com/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(credentials),
          });
          return response.json(); // { user, token }
        },
        register: async (credentials) => {
          const response = await fetch('https://api.example.com/auth/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(credentials),
          });
          return response.json(); // { user, token }
        },
        validateToken: async (token) => {
          const response = await fetch('https://api.example.com/auth/me', {
            headers: { Authorization: `Bearer ${token}` },
          });
          const data = await response.json();
          return data.user;
        },
      }}
    >
      <App />
    </AuthProvider>
  );
}

2. Use the hook in your components

import { useAuth } from '@loonylabs/react-native-offline-auth';

function HomeScreen() {
  const {
    user,
    isAuthenticated,
    isGuestMode,
    login,
    logout,
    continueAsGuest,
  } = useAuth();

  if (isGuestMode) {
    return <Text>Welcome Guest! 👤</Text>;
  }

  if (isAuthenticated) {
    return (
      <View>
        <Text>Welcome {user.username}! 🔐</Text>
        <Button title="Logout" onPress={logout} />
      </View>
    );
  }

  return (
    <View>
      <Button title="Login" onPress={() => login({ email, password })} />
      <Button title="Continue as Guest" onPress={continueAsGuest} />
    </View>
  );
}

Core Concepts

Three Authentication States

  1. Authenticated - User logged in with JWT token
  2. Guest Mode - User using app without account (local data only)
  3. Unauthenticated - User needs to login or continue as guest

Offline-First Philosophy

  • App starts immediately with cached credentials
  • Token validation happens in background (non-blocking)
  • Users stay logged in even when offline
  • No forced logout on network errors

Navigation Logic

function RootNavigator() {
  const { isLoading, isAuthenticated, isGuestMode } = useAuth();

  if (isLoading) {
    return <SplashScreen />;
  }

  if (isAuthenticated || isGuestMode) {
    return <MainApp />;
  }

  return <AuthScreens />;
}

Documentation

Key Features Explained

Guest Mode

Allow users to try your app without registration:

await continueAsGuest();
// User can now use the app with local-only data

Upgrade to Account

Convert guest users to authenticated users:

await upgradeToAccount({
  email: '[email protected]',
  username: 'newuser',
  password: 'securepass123'
});
// Local data is preserved, now synced to cloud

Offline Authentication

Users stay logged in when offline:

// On app start:
// 1. Load token + user from AsyncStorage (instant)
// 2. Show app immediately
// 3. Validate token in background (when online)
// 4. Update user data if validation succeeds
// 5. Stay logged in even if validation fails (offline)

Configuration

<AuthProvider
  apiCallbacks={...}
  config={{
    // Custom storage keys (optional)
    storageKeys: {
      token: '@custom_token',
      user: '@custom_user',
      guestMode: '@custom_guest',
    },
    // Enable debug logging
    debug: true,
    // Custom token validator
    validateToken: async (token) => {
      // Your custom validation logic
      return user;
    },
    // Error callback
    onTokenValidationError: (error) => {
      console.log('Token validation failed:', error);
    },
  }}
  onReady={() => console.log('Auth initialized')}
>
  <App />
</AuthProvider>

TypeScript Support

Fully typed with comprehensive TypeScript definitions:

import type {
  User,
  AuthState,
  LoginCredentials,
  RegisterCredentials,
  AuthConfig,
} from '@loonylabs/react-native-offline-auth';

Testing

The library includes test infrastructure:

npm test              # Run tests
npm run test:watch    # Watch mode
npm run test:coverage # Coverage report

Note: We're actively working on expanding test coverage. Contributions welcome!

Architecture

┌─────────────────────────────────────────────┐
│           React Components                  │
│         (useAuth hook)                      │
└─────────────────┬───────────────────────────┘
                  │
┌─────────────────▼───────────────────────────┐
│         AuthProvider                        │
│    (Zustand Store + Context)                │
└─────────────────┬───────────────────────────┘
                  │
┌─────────────────▼───────────────────────────┐
│         AuthService                         │
│  (Business Logic + Validation)              │
└─────────────────┬───────────────────────────┘
                  │
┌─────────────────▼───────────────────────────┐
│         AuthStorage                         │
│      (AsyncStorage Wrapper)                 │
└─────────────────────────────────────────────┘

Best Practices

✅ DO

  • Use guest mode for better onboarding
  • Load auth state on app start
  • Handle offline scenarios gracefully
  • Validate tokens in background
  • Cache user data locally

❌ DON'T

  • Wait for API calls on app start
  • Logout users on network errors
  • Block UI during token validation
  • Store sensitive data beyond JWT token
  • Force registration before trying the app

Compatibility

  • React Native: 0.70+
  • Expo: ✅ Compatible (SDK 47+)
  • React Native Web: ✅ Compatible
  • iOS: ✅ Tested
  • Android: ✅ Tested

Contributing

Contributions are welcome! Please read our Contributing Guide first.

License

MIT © LoonyLabs

Support

Acknowledgments

Built with:


Made with ❤️ by Loonylabs