Core Concepts
Authentication
CanxJS provides a built-in, comprehensive authentication system supporting JWT, Session, and Role-based access control.
Auth Helpers
Use the auth utility for common tasks like hashing passwords or managing tokens.
src/auth.ts
1import { auth } from "canxjs";23// Hashing Passwords4const hashedPassword = await auth.hash("password123");5const isValid = await auth.verify("password123", hashedPassword);67// JWT Creation8const token = await auth.sign({ sub: user.id }, { secret: process.env.JWT_SECRET });910// Verify Token11const payload = await auth.verifyToken(token, { secret: process.env.JWT_SECRET });
Middleware
Protect your routes using the built-in middlewares.
src/routes.ts
1import { createApp, protect, roles } from "canxjs";23const app = createApp();45const config = { secret: process.env.JWT_SECRET };67// Protect all routes in this group8app.group("/api/private", (router) => {9router.use(protect(config)); // Validates Bearer token1011router.get("/dashboard", (req) => {12const user = req.context.get("user");13return { message: `Hello ${user.sub}` };14});1516// Role-based access control17router.get("/admin", roles("admin"), (req) => {18return { message: "Admin area" };19});20});