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

@fnd-platform/cognito-auth

v1.0.0-alpha.11

Published

AWS Cognito authentication constructs and middleware for fnd-platform applications

Readme

@fnd-platform/cognito-auth

AWS Cognito authentication constructs and middleware for fnd-platform applications. Provides CDK constructs, JWT validation, Lambda authorizers, and Remix authentication utilities.

Installation

npm install @fnd-platform/cognito-auth
# or
pnpm add @fnd-platform/cognito-auth

Quick Start

CDK Construct

import { FndCognitoAuth } from '@fnd-platform/cognito-auth';

const auth = new FndCognitoAuth(this, 'Auth', {
  stage: 'dev',
  appName: 'my-app',
  callbackUrls: ['http://localhost:3000/auth/callback'],
  logoutUrls: ['http://localhost:3000'],
});

// Access outputs
auth.userPool;
auth.userPoolClient;
auth.identityPool;

Lambda Middleware

import { withCognitoAuth } from '@fnd-platform/cognito-auth';

export const handler = withCognitoAuth({
  userPoolId: process.env.USER_POOL_ID!,
  clientId: process.env.CLIENT_ID!,
})(async (event) => {
  // event.requestContext.authorizer contains user claims
  const userId = event.requestContext.authorizer?.claims?.sub;
  return { statusCode: 200, body: JSON.stringify({ userId }) };
});

Remix Authentication

import { requireAuth, getOptionalUser, logout } from '@fnd-platform/cognito-auth';

// In a loader - require authentication
export const loader = async ({ request }) => {
  const user = await requireAuth(request);
  return json({ user });
};

// In a loader - optional authentication
export const loader = async ({ request }) => {
  const user = await getOptionalUser(request);
  return json({ user });
};

// Logout action
export const action = async ({ request }) => {
  return logout(request);
};

Features

  • CDK Construct - Fully configured Cognito User Pool with best practices
  • JWT Validation - Verify and extract claims from Cognito tokens
  • Lambda Middleware - Authenticate Lambda handlers
  • Lambda Authorizer - API Gateway authorizer function
  • Token Refresh - Automatic token refresh utilities
  • Remix Integration - Session management and auth utilities for Remix

CDK Construct Options

interface FndCognitoAuthProps {
  stage: 'dev' | 'staging' | 'prod';
  appName: string;
  callbackUrls: string[];
  logoutUrls: string[];

  // Optional
  selfSignUp?: boolean; // Allow self-registration (default: true)
  mfa?: 'off' | 'optional' | 'required'; // MFA setting (default: 'optional')
  passwordPolicy?: {
    minLength?: number; // Default: 8
    requireUppercase?: boolean; // Default: true
    requireLowercase?: boolean; // Default: true
    requireDigits?: boolean; // Default: true
    requireSymbols?: boolean; // Default: true
  };
}

Examples

Role-Based Access Control

import { requireRole, requireAdmin, hasRole } from '@fnd-platform/cognito-auth';

// Require admin role
export const loader = async ({ request }) => {
  const user = await requireAdmin(request);
  // Only admins can reach this point
  return json({ user });
};

// Require specific roles
export const loader = async ({ request }) => {
  const user = await requireRole(request, ['admin', 'editor']);
  return json({ user });
};

// Check role without redirecting
export const loader = async ({ request }) => {
  const user = await requireAuth(request);
  const isAdmin = hasRole(user, 'admin');
  return json({ user, isAdmin });
};

JWT Verification

import { verifyToken, verifyAndExtract, getVerifier } from '@fnd-platform/cognito-auth';

// Verify a token
const isValid = await verifyToken(token, {
  userPoolId: process.env.USER_POOL_ID!,
  clientId: process.env.CLIENT_ID!,
  tokenUse: 'access',
});

// Verify and get claims
const claims = await verifyAndExtract(token, {
  userPoolId: process.env.USER_POOL_ID!,
  clientId: process.env.CLIENT_ID!,
});

// Get a reusable verifier (cached)
const verifier = getVerifier({
  userPoolId: process.env.USER_POOL_ID!,
  clientId: process.env.CLIENT_ID!,
});

Session Management

import {
  createSessionStorage,
  getSession,
  createUserSession,
  getUserSession,
} from '@fnd-platform/cognito-auth';

// Create session storage
const sessionStorage = createSessionStorage({
  secret: process.env.SESSION_SECRET!,
  secure: process.env.NODE_ENV === 'production',
});

// Create a user session after login
export const action = async ({ request }) => {
  const tokens = await authenticateUser(credentials);
  return createUserSession(request, {
    accessToken: tokens.accessToken,
    idToken: tokens.idToken,
    refreshToken: tokens.refreshToken,
    redirectTo: '/dashboard',
  });
};

Auth Client

import { FndAuthClient, AuthError } from '@fnd-platform/cognito-auth';

const authClient = new FndAuthClient({
  userPoolId: process.env.USER_POOL_ID!,
  clientId: process.env.CLIENT_ID!,
  region: process.env.AWS_REGION!,
});

try {
  // Sign up
  const result = await authClient.signUp({
    email: '[email protected]',
    password: 'SecurePassword123!',
  });

  // Sign in
  const tokens = await authClient.signIn({
    email: '[email protected]',
    password: 'SecurePassword123!',
  });

  // Refresh tokens
  const newTokens = await authClient.refreshTokens(tokens.refreshToken);
} catch (error) {
  if (error instanceof AuthError) {
    console.error(error.code, error.message);
  }
}

API Reference

See the full API documentation for detailed type definitions and examples.

CDK Constructs

  • FndCognitoAuth - Main Cognito User Pool construct
  • FndCognitoAuthProps - Construct configuration
  • Stage - Valid stage values type
  • validateStage - Stage validation utility
  • VALID_STAGES - Array of valid stages

JWT Utilities

import {
  verifyToken, // Verify token validity
  verifyAndExtract, // Verify and return claims
  getVerifier, // Get cached verifier instance
  clearVerifierCache, // Clear verifier cache
} from '@fnd-platform/cognito-auth';

Middleware

import { withCognitoAuth } from '@fnd-platform/cognito-auth';

Lambda Authorizer

import { authorizerHandler } from '@fnd-platform/cognito-auth';

Token Utilities

import { refreshAccessToken, clearClientCache } from '@fnd-platform/cognito-auth';

Auth Client

import { FndAuthClient, AuthError, clearAuthClientCache } from '@fnd-platform/cognito-auth';

Remix Utilities

import {
  // Session management
  createSessionStorage,
  getSession,
  createUserSession,
  getUserSession,
  // Auth helpers
  requireAuth,
  getOptionalUser,
  logout,
  // Role-based access
  requireAdmin,
  requireRole,
  hasRole,
  hasAnyRole,
} from '@fnd-platform/cognito-auth';

Types

import type {
  FndCognitoAuthProps,
  Stage,
  CognitoAccessTokenPayload,
  CognitoIdTokenPayload,
  CognitoAuthOptions,
  JwtVerifierConfig,
  TokenVerificationResult,
  CognitoAuthenticatedEvent,
  CognitoMiddleware,
  CognitoMiddlewareHandler,
  TokenRefreshConfig,
  RefreshResult,
  AuthClientConfig,
  AuthTokens,
  SignUpResult,
  SessionData,
  SessionUser,
  AuthErrorCode,
} from '@fnd-platform/cognito-auth';

Requirements

  • Node.js 20+
  • AWS CDK v2 (for constructs)
  • @remix-run/node (for Remix utilities)

Related

License

MIT