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

@qyh213/easyauth-client

v1.0.0-beta.1

Published

Official client library for Easy Auth - Multi-tenant authentication-as-a-service

Readme

@easyauth/client

Official client library for Easy Auth - Multi-tenant authentication-as-a-service platform.

npm version License: MIT

Features

  • 🔐 Simple Authentication - Login/logout with tokens
  • 🛡️ Token Validation - Validate tokens with easy-auth service
  • 👥 User Management - Create, list, delete users
  • 🔑 API Key Management - Create and revoke service API keys
  • ⚛️ React Integration - Hooks and context for React apps
  • Next.js Support - Middleware and server-side helpers
  • 📘 TypeScript - Full type definitions included

Installation

npm install @easyauth/client
# or
yarn add @easyauth/client
# or
pnpm add @easyauth/client

Quick Start

1. Initialize the Client

import { EasyAuthClient } from "@easyauth/client";

const client = new EasyAuthClient({
  baseUrl: "https://auth.yourservice.com",
  apiKey: "ak-xxxxx",  // Your service API key
});

2. Login a User

// Login and store token
const token = await client.login({
  email: "[email protected]",
  password: "password123",
});

console.log("Logged in! Token expires:", token.expiresAt);

3. Validate Token

// Check if current token is valid
const result = await client.validate();

if (result.valid) {
  console.log("User is authenticated!");
  console.log("Service:", result.serviceId);
  console.log("Scope:", result.scope); // "user", "admin", or "service"
} else {
  console.log("Invalid token:", result.error);
}

4. Logout

await client.logout();
console.log("Logged out!");

React Integration

Setup Provider

import { EasyAuthProvider } from "@easyauth/client/react";

function App() {
  return (
    <EasyAuthProvider
      config={{
        baseUrl: "https://auth.yourservice.com",
        apiKey: "ak-xxxxx",
      }}
    >
      <YourApp />
    </EasyAuthProvider>
  );
}

Use Hooks

import { 
  useIsAuthenticated, 
  useUser, 
  useAuthActions,
  LoginForm 
} from "@easyauth/client/react";

function Dashboard() {
  const isAuthenticated = useIsAuthenticated();
  const user = useUser();
  const { logout } = useAuthActions();

  if (!isAuthenticated) {
    return <LoginForm onSuccess={() => console.log("Logged in!")} />;
  }

  return (
    <div>
      <h1>Welcome, {user?.email}!</h1>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

Protected Component

import { Protected } from "@easyauth/client/react";

function App() {
  return (
    <Protected fallback={<p>Please login...</p>}>
      <SecretContent />
    </Protected>
  );
}

Next.js Integration

Middleware Setup

Create middleware.ts in your project root:

import { createEasyAuthMiddleware } from "@easyauth/client/next";

export const middleware = createEasyAuthMiddleware({
  baseUrl: process.env.EASY_AUTH_URL!,
  protectedPaths: ["/dashboard", "/profile", "/settings"],
  authPaths: ["/login", "/signup"],
  loginPath: "/login",
  dashboardPath: "/dashboard",
});

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

API Route Protection

import { NextResponse } from "next/server";
import { withAuth, withScope } from "@easyauth/client/next";

// Any authenticated user
export const GET = withAuth(
  { baseUrl: process.env.EASY_AUTH_URL! },
  async (request, { userId, scope }) => {
    return NextResponse.json({ 
      message: "Hello user!",
      userId 
    });
  }
);

// Admin only
export const POST = withScope(
  { baseUrl: process.env.EASY_AUTH_URL! },
  ["admin"], // Only admins
  async (request, { userId }) => {
    return NextResponse.json({ 
      message: "Admin action performed" 
    });
  }
);

Server-Side Usage

import { createServerClient } from "@easyauth/client/next";

const serverClient = createServerClient({
  baseUrl: process.env.EASY_AUTH_URL!,
  apiKey: process.env.EASY_AUTH_API_KEY!, // Server-only
});

// Create a user
const user = await serverClient.createUser({
  email: "[email protected]",
  password: "secure123",
});

User Management

Create User (Admin)

const user = await client.createUser({
  email: "[email protected]",
  password: "securePassword123",
});

console.log("Created user:", user.userId);

List Users

const users = await client.listUsers();

users.forEach(user => {
  console.log(`${user.email} (${user.userId})`);
});

Delete User

await client.deleteUser("user-xxxxx");

API Key Management

Create API Key

const key = await client.createApiKey({
  name: "Production Backend",
  scope: "service",
  tpsLimit: 1000,
});

console.log("New API Key (save this!):", key.apiKey);
// ⚠️ Only shown once!

List API Keys

const keys = await client.listApiKeys();

keys.forEach(key => {
  console.log(`${key.name}: ${key.keyId} (${key.revoked ? "revoked" : "active"})`);
});

Revoke API Key

await client.revokeApiKey("key-xxxxx");

Service Onboarding

For platform admins who onboard new services:

import { EasyAuthClient } from "@easyauth/client";

// Use master admin key
const adminClient = new EasyAuthClient({
  baseUrl: "https://auth.yourservice.com",
});

const service = await adminClient.onboardService(
  {
    serviceName: "my-new-service",
    ownerEmail: "[email protected]",
  },
  process.env.MASTER_ADMIN_KEY! // Master onboarding key
);

console.log("Service ID:", service.serviceId);
console.log("Admin API Key (save this!):", service.serviceAdminApiKey);

Token Storage

By default, tokens are stored in localStorage. For custom storage:

import { 
  EasyAuthClient, 
  MemoryTokenStorage 
} from "@easyauth/client";

// Server-side or memory-only storage
const client = new EasyAuthClient(
  { baseUrl: "...", apiKey: "..." },
  new MemoryTokenStorage()
);

Create custom storage:

import { TokenStorage } from "@easyauth/client";

class CookieStorage implements TokenStorage {
  getToken(): string | null {
    // Read from cookies
  }
  setToken(token: string): void {
    // Set cookie
  }
  removeToken(): void {
    // Delete cookie
  }
}

Error Handling

import { EasyAuthError } from "@easyauth/client";

try {
  await client.login({ email, password });
} catch (error) {
  if (error instanceof EasyAuthError) {
    console.log("Error code:", error.code);
    console.log("Status:", error.statusCode);
    console.log("Message:", error.message);
  }
}

Common error codes:

  • MISSING_API_KEY - API key not configured
  • NETWORK_ERROR - Connection failed
  • UNKNOWN_ERROR - Server returned error

Complete Example: Protected API

// middleware.ts
import { createEasyAuthMiddleware } from "@easyauth/client/next";

export const middleware = createEasyAuthMiddleware({
  baseUrl: process.env.EASY_AUTH_URL!,
  protectedPaths: ["/api/protected"],
});

export const config = {
  matcher: "/api/:path*",
};

// app/api/protected/route.ts
import { NextResponse } from "next/server";
import { withAuth } from "@easyauth/client/next";

export const GET = withAuth(
  { baseUrl: process.env.EASY_AUTH_URL! },
  async (request, { userId, scope }) => {
    // User is authenticated!
    return NextResponse.json({
      message: "Secret data",
      userId,
      scope,
    });
  }
);

TypeScript Support

Full TypeScript definitions are included:

import { 
  EasyAuthClient,
  AuthToken,
  User,
  ApiKey,
  ValidationResult,
  EasyAuthConfig 
} from "@easyauth/client";

License

MIT License - see LICENSE file for details.

Contributing

Contributions welcome! Please read our Contributing Guide.

Support