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

nextjs-cognito-auth

v1.5.1

Published

NextAuthSDK SSO/SLO authentication SDK for Next.js apps

Readme

NextAuthSDK

A flexible authentication SDK for Next.js applications with AWS Cognito integration, SSO/SLO support, and session management.

Installation

npm install nextjs-cognito-auth

Quick Start

1. Create your configuration

Create a configuration file (e.g., auth.config.json) with your sensitive data:

{
  "appDomain": "your-app.com",
  "appName": "Your App Name",
  "cognitoRegion": "us-east-1",
  "cognitoUserPoolId": "us-east-1_XXXXXXXXX",
  "cognitoClientId": "your-cognito-client-id",
  "cognitoDomain": "your-cognito-domain.auth.us-east-1.amazoncognito.com",
  "cookieDomain": ".your-app.com",
  "signInPage": "/auth/login",
  "protectedPaths": ["/dashboard", "/profile"],
  "clientIdEndpoint": "/api/public/client-id"
}

2. Initialize the SDK

// app/layout.tsx or _app.tsx
import { AuthProvider, setAuthConfig } from 'nextjs-cognito-auth';
import authConfig from './auth.config.json';

// Initialize the SDK with your configuration
setAuthConfig(authConfig);

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <AuthProvider config={authConfig}>
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

3. Set up NextAuth API route

// app/api/auth/[...nextauth]/route.ts
import { createNextAuthConfig } from 'nextjs-cognito-auth';

const authConfig = {
  clientId: process.env.COGNITO_CLIENT_ID!,
  clientSecret: process.env.COGNITO_CLIENT_SECRET!,
  issuer: process.env.COGNITO_ISSUER!,
  domain: process.env.COOKIE_DOMAIN,
  signInPage: '/auth/login'
};

const handler = createNextAuthConfig(authConfig);
export { handler as GET, handler as POST };

4. Use authentication in your components

import { useAuth, logout } from 'nextjs-cognito-auth';

export default function Dashboard() {
  const { user, isLoading } = useAuth();

  if (isLoading) return <div>Loading...</div>;
  if (!user) return <div>Please log in</div>;

  return (
    <div>
      <h1>Welcome, {user.username}!</h1>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

Single Logout (SLO) Features

The SDK provides robust Single Logout functionality that works across multiple apps:

Automatic Cross-App Logout

When a user logs out from one app, all other apps will automatically detect the logout and sign out the user immediately using multiple detection mechanisms:

  1. BroadcastChannel - Immediate detection for same-origin tabs (fastest)
  2. Storage Events - Cross-tab communication via localStorage
  3. Cookie Polling - Cross-domain detection via shared cookies (500ms intervals)
  4. Visibility/Focus Events - Immediate check when user switches tabs

SessionWatcher Component

The SessionWatcher component automatically handles logout detection:

import { SessionWatcher } from 'nextjs-cognito-auth';

export default function Layout({ children }) {
  return (
    <div>
      <SessionWatcher />
      {children}
    </div>
  );
}

Advanced Logout Detection

For apps that need even more responsive logout handling, use the LogoutDetector utility:

import { LogoutDetector } from 'nextjs-cognito-auth';

const detector = new LogoutDetector({
  onLogout: (timestamp, source) => {
    console.log(`Logout detected from ${source} at ${timestamp}`);
    // Handle immediate logout
  },
  checkInterval: 100 // Check every 100ms for ultra-fast detection
});

detector.start();
// Later: detector.stop();

export default function Dashboard() { const { user, isLoading } = useAuth();

if (isLoading) return Loading...; if (!user) return Please log in;

return ( Welcome, {user.username}! Logout ); }


## Configuration Options

### AuthConfig

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `appDomain` | string | ✅ | Your application domain |
| `appName` | string | ✅ | Your application name |
| `cognitoRegion` | string | ✅ | AWS Cognito region |
| `cognitoUserPoolId` | string | ✅ | Cognito User Pool ID |
| `cognitoClientId` | string | ✅ | Cognito Client ID |
| `cognitoDomain` | string | ✅ | Cognito domain URL |
| `cookieDomain` | string | ❌ | Cookie domain (defaults to `.${appDomain}`) |
| `signInPage` | string | ❌ | Sign-in page path (default: `/auth/login`) |
| `protectedPaths` | string[] | ❌ | Array of protected route patterns |
| `clientIdEndpoint` | string | ❌ | API endpoint for client ID (default: `/api/public/client-id`) |

## Environment Variables

Create a `.env.local` file with your sensitive data:

```env
COGNITO_CLIENT_ID=your-cognito-client-id
COGNITO_CLIENT_SECRET=your-cognito-client-secret
COGNITO_ISSUER=https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX
COOKIE_DOMAIN=.your-app.com

API Reference

Components

  • AuthProvider - Wraps your app with authentication context
  • SessionWatcher - Monitors session changes across tabs

Hooks

  • useAuth() - Get current user and auth state
  • useSession() - Get NextAuth session data

Functions

  • setAuthConfig(config) - Initialize SDK configuration
  • getAuthConfig() - Get current configuration
  • logout() - Sign out user with SSO logout
  • createAuthMiddleware(config) - Create Next.js middleware for route protection
  • createNextAuthConfig(config) - Create NextAuth configuration

Security Best Practices

  1. Never commit sensitive data - Keep your auth.config.json and .env.local files out of version control
  2. Use environment variables for production deployments
  3. Configure proper cookie domains for your environment
  4. Set up HTTPS for production (required for secure cookies)

Example Project Structure

your-app/
├── auth.config.json          # Your configuration (gitignored)
├── .env.local               # Environment variables (gitignored)
├── app/
│   ├── api/
│   │   └── auth/
│   │       └── [...nextauth]/
│   │           └── route.ts
│   ├── auth/
│   │   └── login/
│   │       └── page.tsx
│   └── layout.tsx
└── middleware.ts            # Route protection

License

MIT