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

@nerdlat/auth

v1.0.3

Published

Authentication library similar to Clerk for React and Express applications

Downloads

9

Readme

@nerd/auth

Una librería de autenticación simple e inspirada en Clerk para aplicaciones React y Express.

Instalación

npm install @nerd/auth
# o
yarn add @nerd/auth
# o
pnpm add @nerd/auth

Configuración del Servidor

1. Configuración básica con Express

import express from 'express';
import cookieParser from 'cookie-parser';
import { createAuthRouter } from '@nerd/auth';

const app = express();

app.use(express.json());
app.use(cookieParser());

// Crear y montar las rutas de autenticación
const authRouter = createAuthRouter();
app.use('/api/auth', authRouter);

app.listen(3000);

2. Configuración avanzada

const authRouter = createAuthRouter({
  sessionCookie: 'my-custom-token',
  onUserCreate: (user) => {
    console.log('Usuario creado:', user.email);
    // Enviar email de bienvenida, etc.
  },
  onUserLogin: (user) => {
    console.log('Usuario logueado:', user.email);
    // Analytics, logs, etc.
  },
  validateEmail: (email) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  },
  validatePassword: (password) => {
    return password.length >= 8;
  }
});

3. Proteger rutas

import { requireAuth } from '@nerd/auth';

// Ruta protegida
app.get('/api/protected', requireAuth(), (req, res) => {
  res.json({ 
    message: 'Contenido protegido',
    user: req.user 
  });
});

Configuración del Cliente (React)

1. Envolver tu aplicación con AuthProvider

import { AuthProvider } from '@nerd/auth';

function App() {
  return (
    <AuthProvider fallback={<div>Cargando...</div>}>
      <YourAppContent />
    </AuthProvider>
  );
}

2. Usar los componentes de autenticación

import { SignIn, SignUp, UserProfile, useAuth } from '@nerd/auth';

function AuthSection() {
  const { isSignedIn, isLoading } = useAuth();

  if (isLoading) return <div>Cargando...</div>;

  if (!isSignedIn) {
    return (
      <div>
        <SignIn />
        <SignUp />
      </div>
    );
  }

  return <UserProfile />;
}

3. Usar el hook useAuth

import { useAuth, useUser } from '@nerd/auth';

function MyComponent() {
  const { user, isSignedIn, isLoading, setUser } = useAuth();
  
  // O solo obtener el usuario
  const user = useUser();

  if (!isSignedIn) {
    return <div>Por favor inicia sesión</div>;
  }

  return <div>¡Hola {user.email}!</div>;
}

4. HOC para proteger componentes

import { withAuth } from '@nerd/auth';

const ProtectedComponent = withAuth(function MyComponent() {
  return <div>Este componente solo se muestra a usuarios autenticados</div>;
});

Configuración Personalizada

Si tu API está en una URL diferente o usas un path personalizado:

import { configureAuth } from '@nerd/auth';

// Configurar antes de usar los componentes
configureAuth({
  baseUrl: 'https://mi-api.com',
  apiPath: '/auth' // en lugar de /api/auth
});

Variables de Entorno

Crea un archivo .env en tu proyecto:

AUTH_SECRET=tu-secreto-jwt-muy-seguro
NODE_ENV=production

API Endpoints

La librería crea automáticamente estos endpoints:

  • POST /api/auth/login - Iniciar sesión
  • POST /api/auth/signup - Registrarse
  • GET /api/auth/me - Obtener usuario actual
  • POST /api/auth/logout - Cerrar sesión
  • POST /api/auth/reset-password - Resetear contraseña

Componentes Disponibles

  • <AuthProvider> - Proveedor de contexto de autenticación
  • <SignIn> - Formulario de inicio de sesión
  • <SignUp> - Formulario de registro
  • <UserProfile> - Perfil del usuario con opción de logout
  • <ResetPassword> - Formulario para resetear contraseña

Hooks Disponibles

  • useAuth() - Hook principal con toda la información de auth
  • useUser() - Solo retorna el usuario actual
  • useSession() - Retorna isSignedIn e isLoading

Funciones de Utilidad

  • configureAuth(config) - Configurar URLs personalizadas
  • createAuthRouter(options) - Crear router de Express
  • requireAuth(cookieName?) - Middleware para proteger rutas
  • withAuth(Component) - HOC para proteger componentes

Licencia

MIT