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

@zeo-app/auth-react

v0.3.1

Published

Hooks e guards React para autenticação KKWeb

Downloads

231

Readme

@zeo-app/auth-react

Pacote único de autenticação dos frontends KKWeb: hooks React, guards de rota, store (Zustand), cliente HTTP (Axios) com refresh automático, sincronização entre abas e utilitários de redirect.

Instalação

npm install @zeo-app/auth-react

Peer dependencies (instale no app consumidor):

| Peer dep | Faixa aceita | | ------------------ | ------------ | | react | >=18.0.0 | | react-dom | >=18.0.0 | | react-router-dom | >=6.0.0 | | axios | >=1.0.0 | | zustand | >=4.0.0 |

Desenvolvido e testado contra React 19 + React Router 7.

Uso

1. Criar o cliente e o serviço

// src/lib/auth.ts
import { createApiClient, createAuthService } from '@zeo-app/auth-react';

export const api = createApiClient({
  baseURL: import.meta.env.VITE_API_URL,
  // refreshPath: '/users/refresh',   // default
  // onAuthFailure: () => { ... },    // default: limpa o store
});

export const authService = createAuthService(api);

createApiClient já vem com withCredentials: true (auth por cookie httpOnly) e dois interceptors:

  • refresh — em 401, chama refreshPath uma vez e repete a request original. Requests concorrentes entram numa fila e são liberadas após o refresh. Passe { _skipRefresh: true } no config para desativar numa chamada específica.
  • Content-Type — o client manda application/json por padrão; quando o corpo é FormData, Blob/File ou URLSearchParams, o header é ajustado para o tipo correto (sem isso o axios serializaria um FormData como JSON).

2. Envolver a árvore no provider

Hooks e guards exigem <AuthConfigProvider> acima deles.

import { AuthConfigProvider, initAuthBroadcast } from '@zeo-app/auth-react';
import { authService } from './lib/auth';

initAuthBroadcast(); // sincroniza login/logout entre abas (BroadcastChannel)

<AuthConfigProvider
  authService={authService}
  loginPath="/login"                        // usado por AuthGuard/RoleGuard/useLogout
  shellUrl="https://app.exemplo.com"        // usado por ModuleAuthGuard
  postLoginRoutes={{ super_admin: '/super-admin' }}
>
  <App />
</AuthConfigProvider>;

3. Bootstrap da sessão

function App() {
  useBootstrapAuth(); // chama GET /me e popula o store; libera isBooting
  return <RouterProvider router={router} />;
}

4. Guards de rota

<Route element={<AuthGuard />}>          {/* shell: redirect interno via <Navigate> */}
  <Route path="/modules" element={<Modules />} />
</Route>

<Route element={<GuestGuard />}>         {/* bloqueia /login para quem já entrou */}
  <Route path="/login" element={<Login />} />
</Route>

<Route element={<RoleGuard allow={['super_admin']} />}>
  <Route path="/super-admin" element={<SuperAdmin />} />
</Route>

<Route element={<ModuleAuthGuard />}>    {/* módulos: redirect cross-app via window.location */}
  <Route path="/" element={<ModuleHome />} />
</Route>

AuthGuard, GuestGuard e RoleGuard redirecionam dentro do app (shell). ModuleAuthGuard manda o usuário para o login do shell preservando a URL atual em ?redirect= — use nos frontends de módulo.

Enquanto isBooting é true, todos renderizam <BootScreen />.

5. Hooks

const { login, isLoading, error } = useLogin();   // login + getMe + broadcast + navigate
const logout = useLogout();                       // logout + clearAuth + broadcast + navigate
const hasPermission = usePermission();            // (permission: string) => boolean
const canAccess = useModuleAccess('financeiro');  // boolean

Após o login, useLogin navega para ?redirect= se presente, senão para a rota da role (postLoginRoutes, com defaults super_admin: '/super-admin', admin/user: '/modules').

6. Store

import { useAuthStore } from '@zeo-app/auth-react';

const user = useAuthStore((s) => s.user);
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);

Nota sobre autorização

Guards e hooks de permissão são UX apenas — a autorização real é do backend.

Para gatekeeping de super_admin use RoleGuard, não usePermission: o backend bypassa permissões para essa role, então permissions chega vazio e qualquer checagem por permissão esconderia a UI dele.

API pública

TiposUserRole, UserProfile, AuthMeResponse, LoginCredentials, AuthService, AuthState

API/serviçocreateApiClient, ApiClientConfig, createAuthService

StoreuseAuthStore

ContextoAuthConfigProvider, useAuthConfig

HooksuseBootstrapAuth, useLogin, useLogout, usePermission, useModuleAccess

GuardsAuthGuard, GuestGuard, RoleGuard, ModuleAuthGuard

Sync entre abasinitAuthBroadcast, broadcastLogin, broadcastLogout

UtilsredirectToShellLogin

ComponentesBootScreen

Desenvolvimento

npm run build      # tsup (ESM + CJS + .d.ts)
npm run dev        # build em watch
npm run lint       # ESLint
npm run typecheck  # tsc --noEmit

Para testar mudanças antes de publicar, use file: no app consumidor:

{
  "dependencies": {
    "@zeo-app/auth-react": "file:../kkweb-auth-react"
  }
}