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

@alapandas03/token-refresher

v1.0.4

Published

A service for handling API requests with token refresh capabilities

Readme

@alapandas03/token-refresher

A lightweight, customizable service for handling API requests with automatic token refresh capabilities. Perfect for applications requiring JWT or OAuth2 token management.

Features

  • Automatic token refresh on 401 errors
  • Smart request queuing during token refresh to prevent token race conditions
  • Configurable token storage (localStorage, sessionStorage, or custom storage)
  • Support for all HTTP methods (GET, POST, PUT, DELETE)
  • Fully customizable refresh token endpoint
  • Works in both browser and Node.js environments
  • Built on top of Axios for reliable HTTP requests

Installation

npm install @alapandas03/token-refresher

Quick Start

const TokenRefresher = require('@alapandas03/token-refresher');

const api = new TokenRefresher({
    baseURL: 'https://api.example.com',
    refreshTokenEndpoint: '/auth/refresh'
});

// Example usage
async function fetchUserProfile() {
    try {
        const response = await api.get('/user/profile');
        return response.data;
    } catch (error) {
        console.error('Error:', error);
    }
}

Advanced Usage

1. Custom Token Storage

You can customize where and how tokens are stored by providing custom functions:

const api = new TokenRefresher({
    baseURL: 'https://api.example.com',
    refreshTokenEndpoint: '/auth/refresh',
    // Custom token management functions
    getAccessToken: () => sessionStorage.getItem('my-access-token'),
    getRefreshToken: () => sessionStorage.getItem('my-refresh-token'),
    setAccessToken: (token) => sessionStorage.setItem('my-access-token', token),
    clearTokens: () => {
        sessionStorage.removeItem('my-access-token');
        sessionStorage.removeItem('my-refresh-token');
    }
});

2. Handling Failed Token Refresh

The service automatically handles token refresh failures:

  • Clears existing tokens
  • Rejects all queued requests
  • Throws an error that you can catch to redirect to login
try {
    const response = await api.get('/protected-endpoint');
    return response.data;
} catch (error) {
    if (error.response?.status === 401) {
        // Token refresh failed, redirect to login
        window.location.href = '/login';
    }
}

3. Making Authenticated Requests

// GET request
const getData = await api.get('/endpoint');

// POST request with data
const postData = await api.post('/endpoint', {
    key: 'value'
});

// PUT request
const putData = await api.put('/endpoint', {
    key: 'updated value'
});

// DELETE request
const deleteData = await api.delete('/endpoint');

4. Configuration Options

const api = new TokenRefresher({
    // Required options
    baseURL: 'https://api.example.com',
    refreshTokenEndpoint: '/auth/refresh',

    // Optional token management (defaults to localStorage)
    getAccessToken: () => customStorage.getToken(),
    getRefreshToken: () => customStorage.getRefreshToken(),
    setAccessToken: (token) => customStorage.setToken(token),
    clearTokens: () => customStorage.clear(),

    // Additional axios config options
    timeout: 5000,
    headers: {
        'Custom-Header': 'value'
    }
});

Common Use Cases

  1. Single Page Applications (SPA)

    • Automatic token refresh without interrupting user experience
    • Queued requests continue automatically after token refresh
  2. Mobile-First Applications

    • Efficient token management for intermittent connections
    • Customizable storage for mobile-specific requirements
  3. Microservices Architecture

    • Consistent token management across multiple service calls
    • Centralized refresh token handling
  4. OAuth2 Implementations

    • Perfect for handling OAuth2 access/refresh token flows
    • Automatic token refresh on expiration

Error Handling

The service handles various scenarios:

try {
    const response = await api.get('/endpoint');
    // Success handling
} catch (error) {
    if (error.response) {
        // Server responded with error status
        console.error('Server Error:', error.response.status);
    } else if (error.request) {
        // Request was made but no response
        console.error('Network Error');
    } else {
        // Error in request configuration
        console.error('Request Error:', error.message);
    }
}

Best Practices

  1. Token Storage

    • Use secure storage methods (HttpOnly cookies for refresh tokens)
    • Consider using sessionStorage for access tokens in browsers
  2. Error Handling

    • Implement proper error boundaries
    • Handle token refresh failures gracefully
  3. Security

    • Never store sensitive tokens in localStorage
    • Implement proper CSRF protection

License

MIT

Contributing

Contributions welcome! Please read the contributing guidelines before making a pull request.