kodkodkodkod

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 auth

This will:

  1. Add auth controller, service, and middleware
  2. Update your package.json with required dependencies
  3. Add JWT_SECRET to your .env.example
  4. Update your Prisma schema (if using Prisma)

Setup

After running the command:

1. Install Dependencies

npm install

2. Configure Environment

Add the following to your .env file:

JWT_SECRET=your-super-secret-key-change-this-in-production
JWT_EXPIRES_IN=7d

3. Run Migrations (Prisma)

If using Prisma, run migrations to add the password field:

npx prisma migrate dev --name add-auth

4. 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:

FileDescription
src/auth/auth.service.tsCore auth logic (register, login, tokens)
src/auth/auth.controller.tsHTTP request handlers
src/auth/auth.routes.tsRoute definitions
src/middleware/auth.middleware.tsJWT verification middleware
src/utils/password.utils.tsPassword 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/me endpoint is protected and requires a valid JWT

On this page