{"id":16840,"library":"kroxt","title":"Kroxt: Modular Authentication Engine","description":"Kroxt is a premium, framework-agnostic, and security-hardened authentication engine designed for modern TypeScript environments, currently at stable version 1.3.11. It provides core authentication logic (hashing, JWTs, session management, security features) while allowing developers to implement their own UI and routes, making it 'headless'. Recent releases, particularly v1.3.11, emphasize first-class support for Next.js (App Router) + MongoDB, offering comprehensive tooling and a production-ready developer experience. It maintains modularity through configurable security layers (sessions, rate limiting, IP blocking, password policies) and universal adapters for various ORMs/ODMs like Mongoose, Prisma, and Drizzle. Kroxt differentiates itself with its 'Zero-Config' CLI for quick setup, 100% schema control, and robust security features like real-time session revocation and advanced brute-force protection, adhering to a consistent, active release cadence.","status":"active","version":"1.3.11","language":"javascript","source_language":"en","source_url":"https://github.com/kroxt/kroxt","tags":["javascript","auth","authentication","headless-auth","typescript","security","session-management","token-rotation","argon2"],"install":[{"cmd":"npm install kroxt","lang":"bash","label":"npm"},{"cmd":"yarn add kroxt","lang":"bash","label":"yarn"},{"cmd":"pnpm add kroxt","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for the `kroxt/adapters/mongoose` adapter to interact with MongoDB.","package":"mongoose","optional":true},{"reason":"Required for the `kroxt/adapters/prisma` adapter to interact with SQL databases via Prisma.","package":"@prisma/client","optional":true},{"reason":"Required for the `kroxt/adapters/drizzle` adapter to interact with SQL databases via Drizzle.","package":"drizzle-orm","optional":true}],"imports":[{"note":"Kroxt is designed primarily for ES Modules. CommonJS `require` syntax is generally not supported for its main exports.","wrong":"const { createAuth } = require('kroxt');","symbol":"createAuth","correct":"import { createAuth } from 'kroxt';"},{"note":"Adapter creators are located in specific subpaths (e.g., `kroxt/adapters/mongoose`). Ensure the corresponding ORM/ODM library (e.g., `mongoose`) is installed as a peer dependency in your project.","wrong":"import { createMongoAdapter } from 'kroxt';","symbol":"createMongoAdapter","correct":"import { createMongoAdapter } from 'kroxt/adapters/mongoose';"},{"note":"This refers to the `auth` instance you create and export within your application (e.g., `export const auth = createAuth(...)`). The path shown is common in Next.js projects using path aliases.","symbol":"auth","correct":"import { auth } from '@/lib/kroxt/auth';"}],"quickstart":{"code":"import { createAuth } from \"kroxt\";\nimport { createMongoAdapter } from \"kroxt/adapters/mongoose\";\nimport { NextRequest, NextResponse } from \"next/server\";\n\n// IMPORTANT: Replace this mock with your actual Mongoose User model.\n// Example: import { Schema, model } from 'mongoose';\n// const UserSchema = new Schema({ email: { type: String, unique: true }, password: String, /* ... */ });\n// export const User = model('User', UserSchema);\nconst User = {\n  modelName: 'MockUser',\n  findOne: async (query: any) => {\n    // Simulate finding a user by email for login\n    if (query.email === 'test@example.com') return { email: 'test@example.com', password: 'hashedpassword' };\n    return null;\n  },\n  create: async (data: any) => ({\n    // Simulate user creation\n    _id: 'mockid123',\n    ...data\n  })\n}; // This mock makes the example runnable without a full Mongoose setup.\n\n// 1. Initialize Kroxt authentication engine (e.g., in `lib/kroxt/auth.ts`)\nexport const auth = createAuth({\n  adapter: createMongoAdapter(User),\n  secret: process.env.JWT_SECRET ?? 'super-secret-change-me-in-production',\n  session: { \n    expires: '15m',\n    refreshExpires: '7d',\n    enforceStrictRevocation: true \n  },\n  passwordPolicy: {\n    minLength: 8,\n    requireUppercase: true,\n    requireSpecialCharacter: true,\n    usePepper: false // Set to true if you define process.env.JWT_PEPPER\n  }\n});\n\n// 2. Example Login Route Handler for Next.js App Router (e.g., `app/api/auth/login/route.ts`)\nexport async function POST(req: NextRequest) {\n  try {\n    const { email, password } = await req.json();\n    // `req.ip` might be `undefined` in development or certain environments; provide a fallback.\n    const result = await auth.loginWithPassword(email, password, req.ip ?? 'unknown');\n    \n    // In a real application, you might set cookies or return specific tokens.\n    return NextResponse.json(result, { status: 200 });\n  } catch (error: any) {\n    // Log the error internally but provide a generic message to the client for security.\n    console.error('Login attempt failed:', error.message);\n    return NextResponse.json({ error: error.message || 'Authentication failed' }, { status: 401 });\n  }\n}","lang":"typescript","description":"This quickstart demonstrates how to initialize the Kroxt authentication engine with a Mongoose adapter and implement a basic login route handler using the Next.js App Router, including crucial environment variable handling and a mock User model for immediate testing."},"warnings":[{"fix":"Always define `JWT_SECRET` (and `JWT_PEPPER` if `usePepper` is enabled) as strong, randomly generated strings in your `.env` files for development and secure environment variables for production deployments.","message":"Kroxt relies on critical environment variables like `JWT_SECRET` and optionally `JWT_PEPPER` for cryptographic operations. Failing to define these variables or using insecure defaults will result in runtime errors or severe security vulnerabilities.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For new projects, leverage `npx kroxt init` to scaffold the recommended setup. For existing projects, carefully review the latest documentation for your specific framework/ORM to ensure compatibility and adopt best practices.","message":"While not explicitly termed a 'breaking change,' version 1.3.11 marked a significant architectural shift with first-class support for Next.js (App Router) + MongoDB. Existing integrations in other frameworks or older Next.js setups might require adjustments to align with the new recommended patterns, especially if not using the `kroxt init` CLI.","severity":"breaking","affected_versions":">=1.3.11"},{"fix":"Assess your application's security needs versus performance requirements. For high-security contexts (e.g., admin dashboards), `true` is advisable. For general-purpose APIs with high throughput, consider setting it to `false` and relying on shorter token expiry for eventual revocation.","message":"Enabling `session.enforceStrictRevocation: true` provides real-time session invalidation but incurs a database lookup on every authenticated request. This can significantly impact performance under high traffic loads.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Plan to develop your own frontend and backend API routes. Consult the Kroxt CLI and official boilerplates (e.g., `kroxt-nextjs-mongo`) for examples on how to structure your application and interact with the `auth` instance.","message":"Kroxt is a 'headless' authentication engine; it provides the core logic but no pre-built UI components or routes. Developers are responsible for implementing their own user interfaces (login, signup forms) and API endpoints to interact with Kroxt's functionality.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure the `JWT_SECRET` environment variable is correctly defined and accessible in your application's runtime environment (e.g., `.env` file, server configuration).","cause":"The `secret` option passed to `createAuth` is `undefined`, typically because `process.env.JWT_SECRET` is not set in the application's environment.","error":"Error: JWT_SECRET environment variable is not defined."},{"fix":"Verify that the argument passed to the adapter creator is the correct, instantiated model or client object for your chosen ORM/ODM (e.g., `mongoose.model('User', UserSchema)` for Mongoose, `prisma.user` for Prisma).","cause":"The adapter creator (e.g., `createMongoAdapter`, `createPrismaAdapter`) was initialized with an incorrect, uninstantiated, or incompatible ORM/ODM client or model object.","error":"TypeError: Cannot read properties of undefined (reading 'modelName') / Argument of type 'Model<any, {}, {}, {}, Document<unknown, {}, any>, any>' is not assignable to parameter of type 'never'."},{"fix":"Ensure your project's `package.json` includes `\"type\": \"module\"` and consistently use `import` statements for Kroxt modules. If strictly in CommonJS, consider transpilation or using dynamic `import()` where supported.","cause":"Attempting to use `require()` to import Kroxt modules in a CommonJS context, or if your project is not configured for ES Modules.","error":"SyntaxError: Unexpected token 'export' / Must use import to load ES Module"},{"fix":"Verify that the user account exists in your database. If it's a new user, ensure they have successfully signed up using `auth.signup()` first. Check for typos in the email address during login.","cause":"The `auth.loginWithPassword` method was called with credentials for an email address that does not exist in the database or cannot be retrieved by the configured adapter.","error":"Error: User with provided email not found."}],"ecosystem":"npm","meta_description":null}