Authentication Overview
VeloxTS provides two authentication strategies: JWT and Sessions.
Quick Comparison
Section titled “Quick Comparison”| Feature | JWT | Sessions |
|---|---|---|
| Storage | Client (token) | Server (store) |
| Scalability | Stateless | Requires shared store |
| Revocation | Difficult | Easy |
| Use case | APIs, mobile | Web apps, SSR |
JWT Authentication
Section titled “JWT Authentication”Token-based, stateless authentication with access/refresh token pairs:
import { jwtManager, authPlugin, authenticated } from '@veloxts/auth';
// Configure JWT with access and refresh tokensconst jwt = jwtManager({ secret: process.env.JWT_SECRET!, refreshSecret: process.env.JWT_REFRESH_SECRET!, accessTokenExpiry: '15m', refreshTokenExpiry: '7d',});
app.register(authPlugin, { jwt });
// Protect procedures with guardsgetProfile: procedure() .guard(authenticated) .query(({ ctx }) => ctx.user),Session Authentication
Section titled “Session Authentication”Cookie-based, server-side sessions with secure defaults:
import { sessionMiddleware, inMemorySessionStore } from '@veloxts/auth';
const session = sessionMiddleware({ secret: process.env.SESSION_SECRET!, // 32+ chars store: inMemorySessionStore(), // Use Redis in production cookie: { secure: true, httpOnly: true, sameSite: 'lax', }, userLoader: async (userId) => db.user.findUnique({ where: { id: userId } }),});
// Protect proceduresgetProfile: procedure() .use(session.requireAuth()) .query(({ ctx }) => ctx.user),Guards
Section titled “Guards”Protect procedures with authorization checks:
import { authenticated, hasRole, hasPermission } from '@veloxts/auth';
// Must be logged in.guard(authenticated)
// Must have specific role.guard(hasRole('admin'))
// Must have permission.guard(hasPermission('users:write'))
// Chain multiple guards.guard(authenticated).guard(hasRole('editor'))Guards narrow ctx.user type - after authenticated, ctx.user is guaranteed to exist.
Templates
Section titled “Templates”Quick start with authentication:
npx create-velox-app my-app --authnpx create-velox-app my-app --rsc-auth