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";
2
3// Hashing Passwords
4const hashedPassword = await auth.hash("password123");
5const isValid = await auth.verify("password123", hashedPassword);
6
7// JWT Creation
8const token = await auth.sign({ sub: user.id }, { secret: process.env.JWT_SECRET });
9
10// Verify Token
11const 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";
2
3const app = createApp();
4
5const config = { secret: process.env.JWT_SECRET };
6
7// Protect all routes in this group
8app.group("/api/private", (router) => {
9 router.use(protect(config)); // Validates Bearer token
10
11 router.get("/dashboard", (req) => {
12 const user = req.context.get("user");
13 return { message: `Hello ${user.sub}` };
14 });
15
16 // Role-based access control
17 router.get("/admin", roles("admin"), (req) => {
18 return { message: "Admin area" };
19 });
20});

Next Steps

Learn about Session management.