Skip to content

hacksJuanDavid/BaseKitAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

22 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

BaseKitAPI

Secure, modular, and extensible API starter built with NestJS, Prisma, JWT auth, RBAC, Winston logging, and TypeScript.

Nest Logo

Node NestJS Prisma TypeScript License


✨ What is BaseKitAPI?

BaseKitAPI is a secure and modular API template with JWT authentication (access/refresh), roles (admin, user), users (CRUD), and Prisma ORM. It is ready to grow with business modules, provides structured logs (Winston + Daily Rotate), a success interceptor and a global exception filter for consistent responses, and OpenAPI/Swagger for documentation.

β€œStart small, scale comfortably.”


🧱 Tech Stack

  • NestJS (Modular architecture, dependency injection)
  • TypeScript (end‑to‑end typing, DTOs with class-validator/class-transformer)
  • Prisma (ORM with PostgreSQL, generated client)
  • JWT (access/refresh tokens), RBAC (roles admin, user)
  • Winston + winston-daily-rotate-file (file logs: app, exceptions, success, console)
  • Swagger (@nestjs/swagger) for documentation
  • Throttler (@nestjs/throttler) for rate‑limiting (optional)
  • Passport / @nestjs/passport / passport-jwt

πŸ—‚οΈ Project Structure

BaseKitAPI/src
β”œβ”€β”€ app.module.ts
β”œβ”€β”€ auth
β”‚   β”œβ”€β”€ auth.controller.ts
β”‚   β”œβ”€β”€ auth.module.ts
β”‚   β”œβ”€β”€ auth.service.ts
β”‚   β”œβ”€β”€ decorators
β”‚   β”‚   β”œβ”€β”€ public.decorator.ts
β”‚   β”‚   └── roles.decorator.ts
β”‚   β”œβ”€β”€ dto
β”‚   β”‚   β”œβ”€β”€ login.dto.ts
β”‚   β”‚   β”œβ”€β”€ refres-token.dto.ts
β”‚   β”‚   β”œβ”€β”€ register.dto.ts
β”‚   β”‚   β”œβ”€β”€ token.dto.ts
β”‚   β”‚   └── verify-token.ts
β”‚   β”œβ”€β”€ enums
β”‚   β”‚   └── role.enums.ts
β”‚   β”œβ”€β”€ guards
β”‚   β”‚   β”œβ”€β”€ jwt.guard.ts
β”‚   β”‚   └── roles.guard.ts
β”‚   β”œβ”€β”€ interfaces
β”‚   β”‚   └── payload-token.ts
β”‚   └── strategies
β”‚       └── jwt.strategy.ts
β”œβ”€β”€ logger
β”‚   β”œβ”€β”€ logger.module.ts
β”‚   └── logger.service.ts
β”œβ”€β”€ main.ts
β”œβ”€β”€ middleware
β”‚   β”œβ”€β”€ middleware-all-exceptions-filter.service.ts
β”‚   β”œβ”€β”€ middleware-all-success-interceptor.service.ts
β”‚   └── middleware.module.ts
β”œβ”€β”€ prisma
β”‚   β”œβ”€β”€ prisma.module.ts
β”‚   └── prisma.service.ts
β”œβ”€β”€ security
β”‚   β”œβ”€β”€ password-hasher.service.ts
β”‚   └── security.module.ts
└── user
    β”œβ”€β”€ dto
    β”‚   β”œβ”€β”€ create-user.dto.ts
    β”‚   β”œβ”€β”€ update-password.dto.ts
    β”‚   β”œβ”€β”€ update-user.dto.ts
    β”‚   └── user.dto.ts
    β”œβ”€β”€ user.controller.ts
    β”œβ”€β”€ user.module.ts
    β”œβ”€β”€ user.repository.ts
    └── user.service.ts

πŸš€ Quickstart

1) Requirements

  • Node.js >= 18
  • Yarn or pnpm
  • PostgreSQL running

2) Clone & Install

git clone <your-repo>
cd BaseKitAPI
yarn install

3) Environment Variables

Copy the example and adjust values:

cp .env.example .env

Recommended variables:

# App
NODE_ENV=development
PORT=3000

# Database (PostgreSQL)
DATABASE_URL="postgresql://user:password@localhost:5432/basekitapi?schema=public"

# JWT
JWT_SECRET="super-secret"
JWT_EXPIRES_IN="15m"
JWT_REFRESH_SECRET="another-super-secret"
JWT_REFRESH_EXPIRES_IN="7d"

# Logs
LOG_LEVEL=info
LOG_DIR=logs

# Throttler (optional)
THROTTLE_TTL=60
THROTTLE_LIMIT=60

4) Prisma: init, migrate & generate

# Initialize (creates prisma/schema.prisma and .env if missing)
npx prisma init --datasource-provider postgresql

# Edit prisma/schema.prisma and set client output if you want:
# generator client {
#   provider = "prisma-client-js"
#   output   = "./generated/prisma"  # or ../generated/prisma as you prefer
# }

# Apply initial migration
npx prisma migrate dev --name init

# Generate the client
npx prisma generate

# (Optional) Explore data
npx prisma studio

Note: In this project the Prisma client is exposed via prisma.module.ts / prisma.service.ts. If you change the client output path, update your imports accordingly.

5) Run the API

# Development
yarn start:dev

# Production
yarn build && yarn start:prod

πŸ“˜ API Docs (Swagger)

The app integrates @nestjs/swagger. Check main.ts for Swagger bootstrap and the configured route (defaults to /docs). All DTOs use class-validator and class-transformer to generate models and validate payloads.


πŸ” Authentication & Authorization

JWT Flow

  • /auth/login β†’ returns accessToken (short‑lived) and refreshToken (long‑lived)
  • /auth/refresh-token β†’ receives refreshToken and returns a new token pair
  • /auth/verify β†’ verifies a token
  • /auth/register β†’ user registration

Send the token on each protected request:

Authorization: Bearer <accessToken>

Roles (RBAC)

  • Available roles: admin, user
  • Applied via @Roles() and RolesGuard
  • @Public() marks endpoints that skip the JwtGuard

πŸ‘₯ Key Endpoints

Auth

  • POST /auth/register

    • Example body:

      {
        "email": "user@example.com",
        "password": "Str0ngP@ss!",
        "username": "Ada Lovelace",
        "role": "user"
      }
  • POST /auth/login

    • Body:

      { "email": "user@example.com", "password": "Str0ngP@ss!" }
  • POST /auth/refresh-token

    • Body:

      { "refreshToken": "<token>" }
  • POST /auth/verify

    • Body:

      { "token": "<access_or_refresh_token>" }

Users (JWT‑protected; some require admin)

  • GET /users β†’ list (requires admin)
  • GET /users/:id β†’ detail
  • POST /users β†’ create (may require admin)
  • PATCH /users/:id β†’ update
  • PATCH /users/:id/password β†’ change password
  • DELETE /users/:id β†’ delete (requires admin)

πŸ“¦ Standard Response & Error Handling

Success (global interceptor middleware-all-success-interceptor.service.ts)

Formats successful responses consistently:

{
  "statusCode": 200,
  "message": "Users found",
  "data": [
    /* ... */
  ],
  "meta": {
    /* optional: pagination, etc. */
  }
}

Error (global filter middleware-all-exceptions-filter.service.ts)

Unifies errors into a readable, loggable shape:

{
  "message": "Invalid token",
  "statusCode": 400,
  "timestamp": "2025-08-28T12:34:56.789Z",
  "path": "/auth/verify"
}

πŸ“ Logging (Winston)

  • Log categories with daily rotated files:

    • app β†’ application events
    • exceptions β†’ errors and stack traces
    • success β†’ audit of successful responses
    • console β†’ console output (formatted)
  • Default location: logs/ folder (configurable via LOG_DIR)

  • Each entry includes timestamp, level, context, and relevant payload.

See logger.module.ts / logger.service.ts to customize formats, levels, and transports.


πŸ”’ Security

  • Password hashing via security/password-hasher.service.ts
  • JWT with configurable expiration for access and refresh tokens
  • Rate limiting optional with @nestjs/throttler
  • Strict DTOs with input validation

Make sure to use strong secrets in production and avoid committing .env.


🧩 Prisma & Database

  • Prisma client available via PrismaService

  • Versioned migrations with prisma migrate

  • Useful commands:

    npx prisma migrate dev --name <name>
    npx prisma generate
    npx prisma studio

πŸ§ͺ Common Scripts

# development
yarn start:dev

# production
yarn build && yarn start:prod

# tests (if enabled)
yarn test
yarn test:e2e
yarn test:cov

πŸ”§ CI/CD & Deployment (suggested)

  • PM2 or Docker for production processes
  • Jenkins/GitLab CI for pipelines (build, lint, tests, migrations, deploy)
  • Environment variables injected at runtime

Simple PM2 example:

pm2 start dist/main.js --name basekitapi
pm2 logs basekitapi

🧭 How to Extend (business modules)

  1. Generate a new module (nest g resource <module>) with controller/service/repository.
  2. Define DTOs and validate inputs.
  3. Add Prisma entities and run migrations.
  4. Protect routes with JwtGuard and @Roles() when applicable.
  5. Log key actions (create/update/delete) for traceability.

🀝 Contributing

  1. Fork and create a branch: feat/my-feature
  2. Ensure lint and tests pass
  3. Open a PR describing changes and motivation

πŸ“„ License

MIT


πŸ™Œ Credits

Created by hacksJuanDavid. Built on NestJS and the OSS ecosystem.


πŸ“Ž Appendix: quick dependencies

yarn add prisma @prisma/client

yarn add passport @nestjs/passport @nestjs/jwt passport-jwt

yarn add @nestjs/swagger

yarn add @nestjs/config @nestjs/throttler

yarn add class-transformer class-validator

yarn add winston nest-winston winston-daily-rotate-file

# Types
yarn add -D @types/passport @types/passport-jwt @types/validator

About

Secure, modular, and basic API with authentication, users, roles, and ORM; ready to expand with business modules.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors