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

@bernierllc/contentful-auth

v1.0.8

Published

OAuth 2.0 authentication and token management for Contentful

Readme

@bernierllc/contentful-auth

OAuth 2.0 authentication and token management for Contentful.

Features

  • OAuth 2.0 authorization URL generation
  • Authorization code exchange for access tokens
  • Automatic token refresh with refresh tokens
  • Token validation and expiration checking
  • Secure credential storage interfaces
  • Multi-organization and space-level token management

Installation

npm install @bernierllc/contentful-auth

Usage

Basic Authentication Flow

import { ContentfulAuth, TokenStorage } from '@bernierllc/contentful-auth';

// Create auth instance
const auth = new ContentfulAuth({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  redirectUri: 'https://your-app.com/callback'
});

// Step 1: Generate authorization URL
const authUrl = auth.getAuthorizationUrl('state-value', 'content_management_manage');
// Redirect user to authUrl

// Step 2: Exchange authorization code for tokens
const tokens = await auth.exchangeCodeForTokens(code);
console.log('Access token:', tokens.access_token);
console.log('Refresh token:', tokens.refresh_token);

Token Refresh

// Manually refresh token
const newTokens = await auth.refreshAccessToken(refreshToken);

// Or use automatic refresh with storage
const storage: TokenStorage = {
  async store(key, tokens) {
    // Store tokens in your database
    await db.saveTokens(key, tokens);
  },
  async retrieve(key) {
    // Retrieve tokens from your database
    return await db.getTokens(key);
  },
  async delete(key) {
    // Delete tokens from your database
    await db.deleteTokens(key);
  }
};

const authWithStorage = new ContentfulAuth(config, storage);

// Automatically refreshes if token is expired
const validToken = await authWithStorage.getValidToken('org-123');

Token Validation

const isValid = await auth.validateToken(accessToken);
if (!isValid) {
  console.log('Token is invalid or expired');
}

API

ContentfulAuth

Constructor

constructor(config: ContentfulAuthConfig, storage?: TokenStorage)
  • config.clientId - OAuth client ID
  • config.clientSecret - OAuth client secret
  • config.redirectUri - OAuth redirect URI
  • config.tokenUrl - (Optional) Custom token URL
  • config.authorizationUrl - (Optional) Custom authorization URL
  • config.logger - (Optional) Custom logger instance
  • storage - (Optional) Token storage implementation

Methods

getAuthorizationUrl(state?: string, scope?: string): string

Generate OAuth authorization URL.

exchangeCodeForTokens(code: string): Promise<ContentfulOAuthTokens>

Exchange authorization code for access and refresh tokens.

refreshAccessToken(refreshToken: string): Promise<ContentfulOAuthTokens>

Refresh access token using refresh token.

validateToken(accessToken: string): Promise<boolean>

Validate access token against Contentful API.

getValidToken(storageKey: string): Promise<string>

Get a valid access token, automatically refreshing if expired (requires storage).

storeTokens(key: string, tokens: ContentfulOAuthTokens): Promise<void>

Store tokens (requires storage).

revokeTokens(storageKey: string): Promise<void>

Revoke and delete tokens (requires storage).

TokenStorage Interface

interface TokenStorage {
  store(key: string, tokens: ContentfulOAuthTokens): Promise<void>;
  retrieve(key: string): Promise<ContentfulOAuthTokens | null>;
  delete(key: string): Promise<void>;
}

Implement this interface to provide persistent token storage.

Token Expiration

Tokens are automatically refreshed when:

  • Less than 5 minutes remaining before expiration
  • getValidToken() is called with valid refresh token

Error Handling

try {
  const tokens = await auth.exchangeCodeForTokens(code);
} catch (error) {
  console.error('OAuth failed:', error.message);
}

All methods throw descriptive errors on failure.

Integration

Logger Integration

This package uses @bernierllc/logger for structured logging. The logger is optional and will use a no-op logger if not provided. To enable logging:

import { ContentfulAuth } from '@bernierllc/contentful-auth';
import { Logger } from '@bernierllc/logger';

const logger = new Logger({ level: 'info' });
const auth = new ContentfulAuth({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  redirectUri: 'https://your-app.com/callback',
  logger
});

NeverHub Integration

This package supports optional NeverHub integration for event tracking and monitoring. NeverHub integration is detected automatically and provides graceful degradation if NeverHub is not available.

When NeverHub is available, authentication events (token exchanges, refreshes, validation) are automatically tracked:

import { ContentfulAuth } from '@bernierllc/contentful-auth';
import { NeverHubAdapter } from '@bernierllc/neverhub-adapter';

// NeverHub will be auto-detected if available
const auth = new ContentfulAuth(config);

// Authentication events are automatically logged to NeverHub
await auth.exchangeCodeForTokens(code); // Event tracked in NeverHub

If NeverHub is not available, the package operates normally without event tracking. This ensures the package works in all environments with graceful degradation.

License

Copyright (c) 2025 Bernier LLC. See LICENSE file for details.