Kroxt: Modular Authentication Engine

1.3.11 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

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.

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 });
  }
}

view raw JSON →