Skip to content

klart123/react-auth-kit-lite

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-auth-kit-lite

Tiny, dependency-free login/auth/retry toolkit you can share across React (web) and React Native projects.

It does not assume a specific backend or storage engine — you plug in:

  • a loginFn / refreshFn that call your own API
  • a storage adapter (localStorage for web, AsyncStorage for RN, or in-memory for tests)

Install

npm install react-auth-kit-lite

1. Set up the provider

Web

import { AuthProvider, createWebStorageAdapter } from "react-auth-kit-lite";

const authConfig = {
  storage: createWebStorageAdapter(),
  loginFn: async ({ email, password }) => {
    const res = await fetch("/api/login", {
      method: "POST",
      body: JSON.stringify({ email, password }),
    });
    const data = await res.json();
    return {
      tokens: { accessToken: data.accessToken, refreshToken: data.refreshToken, expiresAt: Date.now() + data.expiresIn * 1000 },
      user: data.user,
    };
  },
  refreshFn: async (refreshToken) => {
    const res = await fetch("/api/refresh", { method: "POST", body: JSON.stringify({ refreshToken }) });
    const data = await res.json();
    return { accessToken: data.accessToken, refreshToken: data.refreshToken, expiresAt: Date.now() + data.expiresIn * 1000 };
  },
};

export function App() {
  return (
    <AuthProvider config={authConfig}>
      <YourApp />
    </AuthProvider>
  );
}

React Native

Same as above, but use the AsyncStorage adapter:

import AsyncStorage from "@react-native-async-storage/async-storage";
import { AuthProvider, createAsyncStorageAdapter } from "react-auth-kit-lite";

const authConfig = {
  storage: createAsyncStorageAdapter(AsyncStorage),
  loginFn: /* same as above */,
  refreshFn: /* same as above */,
};

2. Use it in components

import { useAuth } from "react-auth-kit-lite";

function LoginScreen() {
  const { login, isLoading } = useAuth();

  const onSubmit = async (email: string, password: string) => {
    await login({ email, password }); // retries transient failures automatically
  };
  // ...
}

function Profile() {
  const { user, isAuthenticated, logout } = useAuth();
  if (!isAuthenticated) return <LoginScreen />;
  return <button onClick={logout}>Log out, {user?.name}</button>;
}

3. Authenticated, auto-retrying fetch

fetchWithAuth attaches your access token, retries on network failures (exponential backoff), and transparently refreshes + retries once on a 401:

const { fetchWithAuth } = useAuth();

const res = await fetchWithAuth("/api/orders");
const orders = await res.json();

4. Standalone retry helper

Use withRetry anywhere, auth or not:

import { withRetry } from "react-auth-kit-lite";

const data = await withRetry(() => fetch(url).then((r) => r.json()), {
  retries: 4,
  backoff: "exponential", // or "fixed"
  delayMs: 300,
  shouldRetry: (err) => err instanceof TypeError, // only retry network errors
});

API surface

  • AuthProvider — context provider, takes config: AuthConfig
  • useAuth(){ user, tokens, isAuthenticated, isLoading, login, logout, getValidToken, fetchWithAuth }
  • withRetry(fn, options) — generic async retry/backoff wrapper
  • createWebStorageAdapter() / createAsyncStorageAdapter(AsyncStorage) / createMemoryStorageAdapter()

Publishing

npm run build
npm publish --access public

Then in your other projects: npm install react-auth-kit-lite.

About

authentication method in react, react native

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors