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

@securegraph/sg-nuxt-jwt-sso-bridge

v0.14.0

Published

JWT-based SSO bridge client for Nuxt 3. Connects to external JWT authentication servers with automatic token refresh and session management.

Readme

SG Nuxt JWT SSO Bridge

A JWT-based SSO bridge client for Nuxt 3 applications. This module connects your Nuxt app to an external JWT authentication server with a specific authentication flow:

  • 🌉 Bridge Pattern: Uses a bridge page on the auth domain for token exchange
  • 🔑 JWT Token Relay: Exchanges provider tokens for app-specific JWTs
  • 🔄 Automatic Refresh: Heartbeat interval (default) or on-demand refresh endpoint
  • 🎯 Specific Flow: Designed for /auth/login, /auth/verify, /auth/refresh (with /auth/heartbeat kept for legacy)

Features

  • 🔐 JWT-based authentication
  • 🔄 Automatic session refresh
  • 🛡️ Route protection middleware
  • 🎯 Zero-config setup (almost)
  • 📦 TypeScript support
  • 🚀 SSR compatible

Installation

npm install sg-nuxt-jwt-sso-bridge
# or
yarn add sg-nuxt-jwt-sso-bridge
# or
pnpm add sg-nuxt-jwt-sso-bridge

Configuration

1. Set Environment Variables

# .env
SSO_BASE_URL=https://auth.example.com
SSO_APP_URL=https://myapp.example.com

2. Add Module to nuxt.config.ts

export default defineNuxtConfig({
  modules: ['sg-nuxt-jwt-sso-bridge'],
  
  // Optional: Override default settings
  sso: {
    heartbeatInterval: 840000, // Session refresh interval (ms)
    disableHeartbeat: false,   // Stop interval and use on-demand refresh
    tokenCookieName: 'auth-token', // Cookie name for token storage
    protectedRoutes: ['/dashboard', '/admin'], // Routes requiring auth
    publicRoutes: ['/', '/login', '/about'], // Public routes
    
    // Default login page settings (optional)
    useDefaultLoginPage: true, // Use built-in login page (default: true)
    loginPagePath: '/login', // Path for login page (default: '/login')
    loginPageOptions: {
      title: 'Sign in to continue',
      subtitle: 'Welcome to our application',
      buttonText: 'Sign in with Google',
      organizationName: 'Your Company'
    },
    
    // Token expiration handling (optional)
    onTokenExpired: 'redirect', // 'redirect' | 'reload' | 'none' (default: 'redirect')
    tokenExpiredRedirectPath: '/login', // Redirect path for expired tokens
    tokenExpiredMessage: 'Your session has expired', // Optional message to show
    
    // Callback redirect (optional)
    callbackRedirectPath: '/' // Default redirect after successful login (default: '/')
  }
})

3. That's it! 🎉

The module automatically provides:

  • A beautiful default login page at /login
  • Protected route middleware (sso-auth)
  • Auto-imported useSSO() composable
  • Automatic session management

No additional code required!

Usage

Option 1: Use Default Login Page (Zero Code!)

Just add the module to your config and protect your routes:

<script setup>
// pages/dashboard.vue - This page is protected
definePageMeta({
  middleware: 'sso-auth'  // Users will be redirected to /login if not authenticated
})

const { user } = useSSO()
</script>

<template>
  <div>
    <h1>Welcome, {{ user?.name }}!</h1>
  </div>
</template>

Option 2: Custom Login Implementation

<script setup>
const { user, isAuthenticated, login, logout } = useSSO()
</script>

<template>
  <div>
    <div v-if="isAuthenticated">
      Welcome, {{ user?.name }}!
      <button @click="logout">Logout</button>
    </div>
    <div v-else>
      <button @click="login">Login</button>
    </div>
  </div>
</template>

Option 3: Customize Default Login Page

// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['sg-nuxt-jwt-sso-bridge'],
  sso: {
    loginPageOptions: {
      title: 'Welcome Back',
      subtitle: 'Sign in to access your dashboard',
      buttonText: 'Continue with Google',
      customLogo: '/logo.png',
      organizationName: 'Acme Corp'
    }
  }
})

Protected Routes

<script setup>
// This page requires authentication
definePageMeta({
  middleware: 'sso-auth'
})

const { user } = useSSO()
</script>

<template>
  <div>
    <h1>Dashboard</h1>
    <p>Hello, {{ user?.email }}</p>
  </div>
</template>

Manual Token Verification (Client-side)

const { verifyToken } = useSSO()

// Verify a token manually
const isValid = await verifyToken(token)

Server-side Authentication

The module provides a simple verifyJWT function for server-side token verification:

Basic Usage

// server/api/protected.get.ts
export default defineEventHandler(async (event) => {
  // Get token from header or cookie
  const token = getHeader(event, 'authorization')?.replace('Bearer ', '')
  // or: getCookie(event, 'auth-token')
  
  // Verify token
  const result = await verifyJWT(token)
  
  if (!result.valid) {
    throw createError({
      statusCode: 401,
      statusMessage: result.error || 'Unauthorized'
    })
  }
  
  return {
    user: result.user,
    data: 'Protected data'
  }
})

Auto-imported in Nuxt

The verifyJWT function is automatically available in your server routes - no import needed:

export default defineEventHandler(async (event) => {
  const token = getCookie(event, 'auth-token')
  const { valid, user } = await verifyJWT(token)
  
  if (!valid) {
    return { error: 'Please login' }
  }
  
  return { user, data: '...' }
})

Optional Authentication

export default defineEventHandler(async (event) => {
  const token = getCookie(event, 'auth-token')
  const { valid, user } = await verifyJWT(token)
  
  return {
    publicData: 'Everyone can see this',
    ...(user && { userData: user })
  }
})

Manual Import

If auto-import doesn't work, you can import it directly:

import { verifyJWT } from '@securegraph/sg-nuxt-jwt-sso-bridge/runtime/server/utils/verifyJWT'

Return Value

interface VerifyResponse {
  valid: boolean
  user?: any  // User object from JWT
  error?: string  // Error message if invalid
}

Loading State Management

<script setup>
const { user, loading, checked } = useSSO()
</script>

<template>
  <div>
    <!-- Show loading while authentication is being checked -->
    <div v-if="loading">Checking authentication...</div>
    
    <!-- Show content only after check is complete -->
    <div v-else>
      <div v-if="user">
        Welcome, {{ user.name }}!
      </div>
      <div v-else>
        Please login to continue
      </div>
    </div>
  </div>
</template>

Token Expiration Handling

Configure how the module handles expired tokens:

// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['sg-nuxt-jwt-sso-bridge'],
  sso: {
    // Redirect to login page on token expiration (default)
    onTokenExpired: 'redirect',
    tokenExpiredRedirectPath: '/login',
    tokenExpiredMessage: 'Session expired, please login again',
    
    // OR: Reload the page
    // onTokenExpired: 'reload',
    
    // OR: Do nothing (handle manually)
    // onTokenExpired: 'none'
  }
})

Heartbeat vs On-Demand Refresh

  • Default: interval-based heartbeat keeps the JWT fresh (heartbeatInterval).
  • Opt-out: set disableHeartbeat: true to stop the interval and call heartbeat() on demand (for example, when an API returns 401). heartbeat() hits /auth/refresh and reissues a token if the underlying Clerk session is still active.
  • Legacy clients: /auth/heartbeat remains available and points to the same refresh logic.

API Reference

useSSO()

The main composable for authentication operations.

Returns

  • user - Reactive reference to current user object
  • isAuthenticated - Reactive reference to authentication state
  • checked - Reactive reference to authentication check completion status
  • loading - Reactive reference to loading state (inverse of checked)
  • login(returnTo?: string) - Function to initiate login flow with optional return URL
  • logout() - Function to logout user
  • verifyToken(token: string) - Function to verify a JWT token
  • heartbeat() - Function to refresh session (uses /auth/refresh; call manually when interval is disabled)
  • handleCallback(token: string, returnTo?: string) - Function to handle OAuth callback with optional return URL

⚠️ Important: SSO Server Requirements

This module is designed to work with a specific JWT-based SSO server architecture that implements:

Required Endpoints

  • GET /auth/login?return_to={url} - Initiates OAuth login flow
  • POST /auth/verify - Verifies JWT tokens
    • Request: { token: string }
    • Response: { valid: boolean, user: object }
  • GET /auth/refresh - Refreshes session tokens (preferred)
    • Header: Authorization: Bearer {token}
    • Response: { success: boolean, token: string, user: object }
  • GET /auth/heartbeat - Legacy alias of /auth/refresh
  • GET /auth/callback - Handles OAuth provider callbacks
  • GET /auth/bridge - Bridge page for cross-domain token exchange

Authentication Flow

Standard Login Flow

  1. User visits protected page → Middleware redirects to /login?return_to=/original-page
  2. User clicks login → Redirect to SSO server with callback URL containing return_to
  3. SSO server handles OAuth (Google, GitHub, etc.)
  4. Bridge page exchanges provider token for app JWT
  5. Returns to /auth/callback?token=xxx&return_to=/original-page
  6. Callback verifies token and redirects to original page
  7. Heartbeat (interval) or on-demand refresh (/auth/refresh) keeps the session alive

Token Expiration Flow

  1. Token expires (401 error) during API call → module first tries /auth/refresh once
  2. If refresh fails, behavior depends on onTokenExpired:
    • redirect: Navigate to login page with optional message
    • reload: Refresh the entire page
    • none: Clear auth state, let app handle it
  3. After re-authentication, user returns to their intended destination

Not Compatible With

  • Direct OAuth providers (use @nuxtjs/oauth instead)
  • SAML providers (use nuxt-saml instead)
  • Simple API key auth
  • Firebase Auth, Auth0, Clerk direct integration

Environment Variables

| Variable | Required | Description | |----------|----------|-------------| | SSO_BASE_URL | Yes | Base URL of your SSO service | | SSO_APP_URL | No | Your application URL (default: http://localhost:3000) |

Development

# Install dependencies
yarn install

# Run tests
yarn test

# Build module
yarn prepack

# Run dev server
yarn dev

License

UNLICENSED - This package is proprietary software. All rights reserved.

Support

For questions about this module, please contact your system administrator or the package maintainer.

When NOT to Use This Module

This module is specifically designed for JWT-based SSO bridge architecture.

For other authentication needs, consider:

  • Direct OAuth: @nuxtjs/oauth
  • Auth0: @nuxtjs/auth-next
  • Clerk: @clerk/nuxt
  • Supabase: @nuxtjs/supabase
  • Firebase: @nuxtjs/firebase
  • Generic SSO: @nuxtjs/auth-next