Kroxt: Modular Authentication Engine
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.
Common errors
-
Error: JWT_SECRET environment variable is not defined.
cause The `secret` option passed to `createAuth` is `undefined`, typically because `process.env.JWT_SECRET` is not set in the application's environment.fixEnsure the `JWT_SECRET` environment variable is correctly defined and accessible in your application's runtime environment (e.g., `.env` file, server configuration). -
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'.cause The adapter creator (e.g., `createMongoAdapter`, `createPrismaAdapter`) was initialized with an incorrect, uninstantiated, or incompatible ORM/ODM client or model object.fixVerify 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). -
SyntaxError: Unexpected token 'export' / Must use import to load ES Module
cause Attempting to use `require()` to import Kroxt modules in a CommonJS context, or if your project is not configured for ES Modules.fixEnsure 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. -
Error: User with provided email not found.
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.fixVerify 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.
Warnings
- gotcha 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.
- breaking 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install kroxt -
yarn add kroxt -
pnpm add kroxt
Imports
- createAuth
const { createAuth } = require('kroxt');import { createAuth } from 'kroxt'; - createMongoAdapter
import { createMongoAdapter } from 'kroxt';import { createMongoAdapter } from 'kroxt/adapters/mongoose'; - auth
import { auth } from '@/lib/kroxt/auth';
Quickstart
import { createAuth } from "kroxt";
import { createMongoAdapter } from "kroxt/adapters/mongoose";
import { NextRequest, NextResponse } from "next/server";
// IMPORTANT: Replace this mock with your actual Mongoose User model.
// Example: import { Schema, model } from 'mongoose';
// const UserSchema = new Schema({ email: { type: String, unique: true }, password: String, /* ... */ });
// export const User = model('User', UserSchema);
const User = {
modelName: 'MockUser',
findOne: async (query: any) => {
// Simulate finding a user by email for login
if (query.email === 'test@example.com') return { email: 'test@example.com', password: 'hashedpassword' };
return null;
},
create: async (data: any) => ({
// Simulate user creation
_id: 'mockid123',
...data
})
}; // This mock makes the example runnable without a full Mongoose setup.
// 1. Initialize Kroxt authentication engine (e.g., in `lib/kroxt/auth.ts`)
export const auth = createAuth({
adapter: createMongoAdapter(User),
secret: process.env.JWT_SECRET ?? 'super-secret-change-me-in-production',
session: {
expires: '15m',
refreshExpires: '7d',
enforceStrictRevocation: true
},
passwordPolicy: {
minLength: 8,
requireUppercase: true,
requireSpecialCharacter: true,
usePepper: false // Set to true if you define process.env.JWT_PEPPER
}
});
// 2. Example Login Route Handler for Next.js App Router (e.g., `app/api/auth/login/route.ts`)
export async function POST(req: NextRequest) {
try {
const { email, password } = await req.json();
// `req.ip` might be `undefined` in development or certain environments; provide a fallback.
const result = await auth.loginWithPassword(email, password, req.ip ?? 'unknown');
// In a real application, you might set cookies or return specific tokens.
return NextResponse.json(result, { status: 200 });
} catch (error: any) {
// Log the error internally but provide a generic message to the client for security.
console.error('Login attempt failed:', error.message);
return NextResponse.json({ error: error.message || 'Authentication failed' }, { status: 401 });
}
}