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

netreq-auth

v0.1.1

Published

Authentication plugin for netreq. JWT token management with automatic refresh and storage adapters.

Readme

@netreq/auth

JWT authentication plugin for netreq. Handles tokens, auto-refresh, and storage.

Install

npm install @netreq/auth

Quick Start

import { createClient } from 'netreq';
import { Auth, WebStorage } from '@netreq/auth';

const auth = new Auth({
  storage: new WebStorage('localStorage'),
  refreshEndpoint: '/api/auth/refresh',
  onSessionExpired: () => {
    window.location.href = '/login';
  }
});

const client = createClient({
  baseUrl: 'https://api.example.com'
});

client.use(auth.middleware());

// Login
await auth.login('/api/auth/login', {
  email: '[email protected]',
  password: 'secret'
});

// All requests now include Authorization header
// 401 responses trigger automatic token refresh
const user = await client.get('/me');

How It Works

  1. Auto Header Injection - Adds Authorization: Bearer <token> to every request
  2. Token Refresh - On 401 error, automatically refreshes token and retries the request
  3. Request Queue - While refreshing, other requests wait in queue. After refresh, all retry with new token.
  4. Storage Adapter - Tokens persist in localStorage/sessionStorage/memory/cookies

Storage Options

import { Auth, MemoryStorage, WebStorage, CookieStorage } from '@netreq/auth';

// Browser with persistence
const auth = new Auth({
  storage: new WebStorage('localStorage', 'myapp_tokens'),
  refreshEndpoint: '/api/auth/refresh'
});

// Server-side / SSR
const auth = new Auth({
  storage: new MemoryStorage(),
  refreshEndpoint: '/api/auth/refresh'
});

// Cookies
const auth = new Auth({
  storage: new CookieStorage({
    name: 'auth',
    secure: true,
    sameSite: 'strict'
  }),
  refreshEndpoint: '/api/auth/refresh'
});

Configuration

const auth = new Auth({
  // Required
  refreshEndpoint: '/api/auth/refresh',
  
  // Optional
  storage: new WebStorage('localStorage'),
  refreshMethod: 'POST',
  authHeaderName: 'Authorization',
  tokenPrefix: 'Bearer ',
  maxRefreshRetries: 3,
  refreshTimeout: 10000,
  
  // Transform refresh request/response
  buildRefreshBody: (refreshToken) => ({ token: refreshToken }),
  extractTokenPair: (response) => ({
    accessToken: response.data.access_token,
    refreshToken: response.data.refresh_token
  }),
  
  // Events
  onLogin: () => console.log('Logged in'),
  onLogout: () => console.log('Logged out'),
  onTokenRefreshed: () => console.log('Token refreshed'),
  onSessionExpired: () => {
    // Redirect to login
    window.location.href = '/login';
  }
});

API Methods

// Check auth status
auth.isAuthenticated(); // boolean
auth.getAccessToken();  // string | null

// Manual login/logout
await auth.login('/api/login', { email, password });
await auth.logout();

// Manual token management
await auth.setTokens({
  accessToken: 'xxx',
  refreshToken: 'yyy'
});

Custom Storage

import type { TokenStorage, TokenPair } from '@netreq/auth';

class EncryptedStorage implements TokenStorage {
  async getTokens(): Promise<TokenPair | null> {
    const encrypted = localStorage.getItem('tokens');
    return encrypted ? decrypt(encrypted) : null;
  }
  
  async setTokens(tokens: TokenPair): Promise<void> {
    localStorage.setItem('tokens', encrypt(tokens));
  }
  
  async clearTokens(): Promise<void> {
    localStorage.removeItem('tokens');
  }
}

const auth = new Auth({
  storage: new EncryptedStorage(),
  refreshEndpoint: '/api/auth/refresh'
});

React Example

See examples/react-integration.ts for full Context API setup.

// AuthProvider.tsx
const auth = new Auth({
  storage: new WebStorage('localStorage'),
  refreshEndpoint: '/api/auth/refresh'
});

client.use(auth.middleware());

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  
  const login = async (email, password) => {
    await auth.login('/api/login', { email, password });
    const res = await client.get('/me');
    setUser(res.data);
  };
  
  return (
    <AuthContext.Provider value={{ user, login }}>
      {children}
    </AuthContext.Provider>
  );
}

Requirements

  • Node.js 18+
  • netreq 0.1.0+

License

MIT