Authentication Module
Add JWT-based authentication to your kodkod project.
Authentication Module
Add secure JWT-based authentication to your project with a single command.
Installation
Navigate to your kodkod project and run:
npx kodkod-stack add authThis will:
- Add auth controller, service, and middleware
- Update your
package.jsonwith required dependencies - Add
JWT_SECRETto your.env.example - Update your Prisma schema (if using Prisma)
Setup
After running the command:
1. Install Dependencies
npm install2. Configure Environment
Add the following to your .env file:
JWT_SECRET=your-super-secret-key-change-this-in-production
JWT_EXPIRES_IN=7d3. Run Migrations (Prisma)
If using Prisma, run migrations to add the password field:
npx prisma migrate dev --name add-auth4. Register Auth Routes
Import and register the auth routes in your main application file:
Express:
import authRoutes from './auth/auth.routes.js';
app.use('/auth', authRoutes);Hono:
import auth from './auth/auth.routes.js';
app.route('/auth', auth);Fastify:
import authRoutes from './auth/auth.routes.js';
fastify.register(authRoutes);API Endpoints
Register a New User
POST /auth/register
Content-Type: application/json
{
"email": "user@example.com",
"password": "securepassword123",
"name": "John Doe"
}Response:
{
"user": {
"id": "clx...",
"email": "user@example.com",
"name": "John Doe"
},
"token": "eyJhbG..."
}Login
POST /auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "securepassword123"
}Response:
{
"user": {
"id": "clx...",
"email": "user@example.com",
"name": "John Doe"
},
"token": "eyJhbG..."
}Get Current User (Protected)
GET /auth/me
Authorization: Bearer <token>Response:
{
"id": "clx...",
"email": "user@example.com",
"name": "John Doe"
}Files Added
The auth module adds the following files to your project:
| File | Description |
|---|---|
src/auth/auth.service.ts | Core auth logic (register, login, tokens) |
src/auth/auth.controller.ts | HTTP request handlers |
src/auth/auth.routes.ts | Route definitions |
src/middleware/auth.middleware.ts | JWT verification middleware |
src/utils/password.utils.ts | Password hashing utilities |
Protecting Routes
Use the authGuard middleware to protect your routes:
Express:
import { authGuard, AuthenticatedRequest } from './middleware/auth.middleware.js';
app.get('/protected', authGuard, (req: AuthenticatedRequest, res) => {
const userId = req.user?.userId;
res.json({ message: `Hello, user ${userId}` });
});Security Considerations
Important: Always use a strong, unique JWT_SECRET in production. Never commit secrets to version control.
- Passwords are hashed using bcrypt with 10 salt rounds
- JWTs expire after 7 days by default (configurable via
JWT_EXPIRES_IN) - The
/auth/meendpoint is protected and requires a valid JWT
