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

saget-auth-middleware

v2.1.2

Published

A comprehensive authentication middleware for Node.js applications with SSO integration, JWT validation, and role-based access control

Readme

SAGET Auth Middleware

A comprehensive, production-ready authentication middleware for Node.js applications that integrates with SAGET SSO system. This package provides a drop-in replacement for your existing SSO middleware with enhanced features and better error handling.

🚀 Quick Start (Drop-in Replacement)

Replace your existing middleware.js file with this simple setup:

// middleware.js
import { middleware, configureMiddleware, config } from 'saget-auth-middleware';

// Optional: Configure for your specific needs
configureMiddleware({
  PUBLIC_PATHS: ['/', '/login', '/register', '/docs'],
  ACCESS_CONTROL: {
    '/dashboard': ['SUPER ADMIN'],
    '/account': ['SUPER ADMIN', 'GUEST', 'USER', 'ADMIN', 'APPLICANT']
  }
});

export { middleware as default, config };

That's it! Your middleware now has all the features of your original SSO middleware plus:

JWT token verification using jose library
Automatic token refresh with proper error handling
Role-based access control (RBAC)
Configurable public paths
SSO login redirect with proper parameters
Cookie management with security best practices
Comprehensive error handling and logging
Environment variable support with fallbacks
Docker network compatibility

📦 Installation

npm install saget-auth-middleware
# or
yarn add saget-auth-middleware

🛠️ CLI Generator (Simplified)

Generate middleware files directly in your project root with a single command:

# Generate TypeScript files for Next.js (most common)
npx saget-auth-middleware init

# Or specify options
npx saget-auth-middleware init --type ts --framework next

# Generate JavaScript files for Express
npx saget-auth-middleware init --type js --framework express

# Generate in a specific directory
npx saget-auth-middleware init --output ./auth

What gets generated:

  • middleware.ts/js - Main middleware file
  • types.ts (TypeScript only) - Type definitions
  • auth-utils.ts/js - Client-side utilities
  • .env.example - Environment configuration template
  • README.md - Usage documentation

Default behavior: Files are generated directly in your current directory (no subdirectory created).

🔧 Environment Variables

Required Variables

# JWT Secret for token verification
SSO_JWT_SECRET=your-jwt-secret-key

# SSO App Configuration
SSO_APP_KEY=your-sso-app-key
# or
NEXT_PUBLIC_APP_KEY=your-sso-app-key

# Redirect URL after SSO login
NEXT_PUBLIC_REDIRECT_URL=https://yourapp.com/login/callback
# or
NEXT_REDIRECT_URL=https://yourapp.com/login/callback

# SSO API URL
SSO_API_URL=https://your-sso-api.com
# or
NEXT_PUBLIC_API_URL=https://your-sso-api.com

Optional Variables

# Custom SSO login URL
SSO_LOGIN_URL=https://your-sso-server.com/login

# Server-side API URL (for Docker networks)
NEXT_PUBLIC_API_URL_SERVER_SIDE=http://sso-api:3000

# Custom cookie names
NEXT_PUBLIC_COOKIE_ACCESS_TOKEN_NAME=accessToken-yourapp.com
NEXT_PUBLIC_COOKIE_REFRESH_TOKEN_NAME=refreshToken-yourapp.com
NEXT_PUBLIC_COOKIE_APPLICATION_TOKEN_NAME=applicationToken-yourapp.com

🎯 Usage Examples

Basic Usage (Minimal Setup)

// middleware.js
import { middleware, config } from 'saget-auth-middleware';

export { middleware as default, config };

📁 See examples/simple-usage.js for complete basic setup

Advanced Configuration

// middleware.js
import { middleware, configureMiddleware, config } from 'saget-auth-middleware';

configureMiddleware({
  // Public paths that bypass authentication
  PUBLIC_PATHS: [
    '/',
    '/login',
    '/register',
    '/docs',
    '/about',
    '/contact',
    '/login/verify-otp'
  ],
  
  // Role-based access control
  ACCESS_CONTROL: {
    '/dashboard': ['SUPER ADMIN'],
    '/admin': ['SUPER ADMIN', 'ADMIN'],
    '/account': ['SUPER ADMIN', 'GUEST', 'USER', 'ADMIN', 'APPLICANT'],
    '/reports': ['SUPER ADMIN', 'ADMIN'],
    '/settings': ['SUPER ADMIN']
  },
  
  // Custom cookie names
  COOKIE_NAMES: {
    ACCESS_TOKEN: 'accessToken-myapp.com',
    REFRESH_TOKEN: 'refreshToken-myapp.com',
    APPLICATION_TOKEN: 'applicationToken-myapp.com'
  },
  
  // Custom SSO login URL
  SSO_LOGIN_URL: 'https://sso.mycompany.com/login'
});

export { middleware as default, config };

📁 See examples/advanced-config.js for all configuration options

Using with Express.js

// app.js
import express from 'express';
import { middleware } from 'saget-auth-middleware';

const app = express();

// Apply SSO middleware to all routes
app.use(middleware);

app.get('/dashboard', (req, res) => {
  res.json({ message: 'Protected dashboard' });
});

app.listen(3000);

📁 See examples/express/app.js for complete Express.js setup

🔐 Authentication Flow

The middleware follows the exact same flow as your original SSO middleware:

  1. Public Path Check: Allows access to configured public paths
  2. Token Validation: Verifies JWT access token using jose library
  3. Token Refresh: Automatically refreshes expired tokens using refresh token
  4. Authorization Check: Validates user roles against path requirements
  5. SSO Redirect: Redirects to SSO login if authentication fails

🛡️ Security Features

  • JWT Verification: Uses industry-standard jose library for token verification
  • Automatic Token Refresh: Seamlessly refreshes expired tokens
  • Secure Cookies: HttpOnly, Secure, SameSite protection
  • Role-Based Access Control: Fine-grained permission system
  • Error Handling: Comprehensive error logging and recovery
  • Environment Validation: Validates required configuration

🔄 Migration from Original Middleware

Before (Original Middleware)

// middleware.js - 300+ lines of code
import { NextResponse } from "next/server";
import { JsonWebTokenError } from "jsonwebtoken";
import { jwtVerify } from "jose";

const PUBLIC_PATHS = ['/', '/login', '/register'];
const ACCESS_CONTROL = { /* ... */ };

const decodeJwtToken = async (token) => { /* ... */ };
const checkOtorisasi = async (req) => { /* ... */ };
const setCookieFromReauth = async (refreshToken) => { /* ... */ };
// ... 200+ more lines

export async function middleware(req) {
  // ... complex logic
}

After (SAGET Auth Middleware)

// middleware.js - 3 lines of code!
import { middleware, config } from 'saget-auth-middleware';

export { middleware as default, config };

📚 API Reference

configureMiddleware(config)

Configure the middleware with custom settings.

configureMiddleware({
  PUBLIC_PATHS: string[],      // Paths that bypass authentication
  ACCESS_CONTROL: object,      // Role-based access control rules
  COOKIE_NAMES: object,        // Custom cookie names
  SSO_LOGIN_URL: string        // Custom SSO login URL
});

middleware(request)

The main middleware function that handles authentication.

  • Parameters: request - Next.js request object
  • Returns: NextResponse - Response with authentication handling

🧪 Testing

# Run integration tests
npm test

# Run with coverage
npm run test:coverage

# Run in watch mode
npm run test:watch

🐛 Troubleshooting

Common Issues

  1. "SSO_JWT_SECRET environment variable is not set"

    • Ensure SSO_JWT_SECRET is set in your environment variables
  2. "Failed to refresh tokens"

    • Check your SSO_API_URL is correct and accessible
    • Verify your refresh token endpoint is working
  3. "User not authorized for path"

    • Check your ACCESS_CONTROL configuration
    • Verify user roles in the application token
  4. Token refresh loops

    • Ensure your SSO API returns valid tokens
    • Check network connectivity to SSO API

Debug Mode

Enable detailed logging by setting:

NODE_ENV=development

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🏢 About PIJAR TEKNOLOGI

This middleware is developed and maintained by PIJAR TEKNOLOGI. For enterprise support and custom implementations, please contact us.


Made with ❤️ by PIJAR TEKNOLOGI