Skip to content

A scaffolding CLI that instantly generates complete, production-ready Express apps with TypeScript/JavaScript, auth, DBs, ORMs, and Docker support.

License

Notifications You must be signed in to change notification settings

SnoWed-29/Scaff-js

ScaffJs CLI

npm version Node Version License Platform GitHub issues

Production-Ready Express.js Project Scaffolding CLI

Generate complete, tested, and deployable Express applications in seconds with TypeScript/JavaScript support, authentication, databases, ORMs, and Docker integration.


Table of Contents


Features

Core Capabilities

Feature Description
Language Support TypeScript (recommended) or JavaScript
Architecture Patterns MVC (Model-View-Controller) structure
Authentication JWT + Sessions + Refresh Tokens with bcrypt
Database Support PostgreSQL and MySQL
ORM Integration Prisma (recommended) or Sequelize
Docker Ready Dockerfile + docker-compose with health checks
Automated Testing 6+ built-in test suites run on generation

Production-Ready Features

  • Health Endpoints - /health and /ready for container orchestration
  • Graceful Shutdown - Proper SIGTERM/SIGINT handling with connection cleanup
  • Session Support - Express-session configured (user configures store for production)
  • Environment Configuration - Comprehensive .env setup
  • Error Handling - Global error middleware with proper logging
  • Security - CORS, bcrypt hashing, JWT validation, secure cookies

Developer Experience

  • Interactive Prompts - Guided project setup with validation
  • Dry Run Mode - Preview project structure before creation
  • Verbose Logging - Detailed output for debugging
  • Rollback System - Automatic cleanup on errors
  • Performance Optimized - Concurrent file operations and caching
  • Cross-Platform - Works on Windows, macOS, and Linux

Quick Start

# Install globally
npm install -g scaffjs-cli

# Create a project interactively
scaffjs create

# Or create with specific options
scaffjs create my-api --ts --auth --pg --prisma --dockerAll

# Preview before creating
scaffjs create my-api --ts --dry-run

Installation

Global Installation (Recommended)

npm install -g scaffjs-cli

Using npx (No Installation)

npx scaffjs-cli create my-app

Local Development

git clone https://github.com/SnoWed-29/Scaff-js.git
cd Scaff-js
npm install
npm run build
npm link

Usage

Interactive Mode

Run without arguments to enter guided setup:

scaffjs create

You'll be prompted for:

  1. Project name
  2. Language (TypeScript/JavaScript)
  3. Authentication (Yes/No)
  4. Database (None/PostgreSQL/MySQL)
  5. ORM (None/Prisma/Sequelize) - if database selected
  6. Docker (None/Dockerfile/Full Stack) - if database selected

Command-Line Flags

Create projects directly with flags:

scaffjs create <project-name> [options]

CLI Options Reference

Language Selection (mutually exclusive)

Flag Description
--ts Use TypeScript with strict mode, type definitions, and build scripts
--js Use JavaScript with ES6 modules

Authentication

Flag Description
--auth Add JWT authentication with register, login, refresh, and logout endpoints

Database (mutually exclusive)

Flag Description
--pg PostgreSQL database connection
--mysql MySQL database connection

ORM (requires database, mutually exclusive)

Flag Description
--prisma Prisma ORM with schema, migrations, and type-safe queries
--sequelize Sequelize ORM with models and automatic sync

Docker (mutually exclusive)

Flag Description
--docker Generate Dockerfile only
--dockerAll Generate Dockerfile + docker-compose.yml with database service

Utility Flags

Flag Description
--dry-run Preview project structure without creating files
--verbose Show detailed logs and test results during generation
--no-install Skip automatic npm install
--no-test Skip automatic testing after generation

Examples

Full-Featured TypeScript API

scaffjs create my-api --ts --auth --pg --prisma --dockerAll

Creates a TypeScript API with:

  • MVC architecture
  • JWT authentication
  • PostgreSQL database
  • Prisma ORM
  • Docker + Docker Compose setup

Minimal JavaScript API

scaffjs create simple-api --js

Creates a basic JavaScript Express server with MVC structure.

Full Stack with MySQL

scaffjs create enterprise-app --ts --auth --mysql --sequelize --dockerAll

Creates a TypeScript API with:

  • MVC architecture
  • JWT authentication
  • MySQL database
  • Sequelize ORM
  • Docker + Docker Compose setup

Preview Mode

scaffjs create my-api --ts --auth --pg --prisma --dry-run

Shows the project structure without creating any files.

Fast Generation (Skip Install & Tests)

scaffjs create prototype --ts --no-install --no-test

Generates files only, skipping npm install and tests.


Generated Project Structure

MVC Structure

my-project/
├── src/
│   ├── controllers/
│   │   ├── hello.controller.ts
│   │   └── auth.controller.ts        # if --auth
│   ├── models/
│   │   ├── User.ts                   # if --auth with Sequelize
│   │   └── Session.ts                # if --auth with Sequelize
│   ├── routes/
│   │   ├── hello.routes.ts
│   │   └── auth.routes.ts            # if --auth
│   ├── middleware/
│   │   └── auth.ts                   # if --auth
│   ├── database/
│   │   ├── connection.ts             # if database without ORM
│   │   └── sequelize.ts              # if --sequelize
│   ├── config/
│   │   └── index.ts
│   ├── utils/
│   │   └── jwt.ts                    # if --auth
│   └── index.ts
├── prisma/
│   ├── schema.prisma                 # if --prisma
│   └── migrations/                   # if --prisma --dockerAll
├── dist/                             # if TypeScript (compiled output)
├── package.json
├── tsconfig.json                     # if TypeScript
├── Dockerfile                        # if --docker or --dockerAll
├── docker-compose.yml                # if --dockerAll
├── docker-entrypoint.sh              # if --prisma --dockerAll
├── .dockerignore                     # if --docker or --dockerAll
├── .env.example
├── .gitignore
├── .scaffjs.json
└── README.md

API Endpoints

Health Endpoints (Always Included)

Method Endpoint Description Response
GET /health Liveness probe { status: "ok", timestamp, uptime }
GET /ready Readiness probe (checks DB) { status: "ready", timestamp }

Application Endpoints

Method Endpoint Description Response
GET /hello Hello World test { message: "Hello World!" }

Authentication Endpoints (if --auth)

Method Endpoint Description Request Body Response
POST /auth/register Create account { email, password, name } { message, userId }
POST /auth/login Get tokens { email, password } { accessToken, refreshToken, user }
POST /auth/refresh Renew access token { refreshToken } { accessToken }
POST /auth/logout Invalidate session { refreshToken } { message }

Configuration

Environment Variables

Create a .env file from .env.example:

Linux/macOS:

cp .env.example .env

Windows (PowerShell):

Copy-Item .env.example .env

Windows (CMD):

copy .env.example .env

Core Variables

PORT=3000
NODE_ENV=development

Database Variables

DB_HOST=localhost
DB_PORT=5432                          # PostgreSQL: 5432, MySQL: 3306
DB_NAME=my_database
DB_USER=postgres                      # or your database user
DB_PASSWORD=your_password
DATABASE_URL=postgresql://user:pass@localhost:5432/db  # For Prisma

Authentication Variables

JWT_SECRET=your-super-secret-jwt-key
JWT_REFRESH_SECRET=your-refresh-secret-key
JWT_EXPIRES_IN=15m
JWT_REFRESH_EXPIRES_IN=7d
SESSION_SECRET=your-session-secret

Production Session Store (User Configuration Required)

The generated project uses in-memory session storage by default. For production, you should configure a persistent session store like Redis or MongoDB:

# Example: Redis session store (requires additional setup)
SESSION_STORE=redis
REDIS_URL=redis://localhost:6379

# Example: MongoDB session store (requires additional setup)
SESSION_STORE=mongo
MONGODB_URL=mongodb://localhost:27017/sessions

Note: You will need to install and configure the session store package (e.g., connect-redis, connect-mongo) in your generated project.


Docker Support

Dockerfile Features

  • Multi-stage builds for TypeScript (smaller production images)
  • Alpine-based images (node:18-alpine)
  • Health checks built-in
  • Prisma client generation during build
  • Production dependencies only in final image

Docker Compose Features

When using --dockerAll:

  • Application service on port 3000
  • Database service (PostgreSQL or MySQL)
  • Health checks with proper startup delays
  • Volume persistence for database data
  • Environment variables pre-configured
  • Automatic migrations for Prisma

Running with Docker

Docker Compose v2 (recommended):

docker compose up -d

Docker Compose v1:

docker-compose up -d

Build and run separately:

docker compose build
docker compose up -d

View logs:

docker compose logs -f app

Stop services:

docker compose down

Stop and remove volumes:

docker compose down -v

Database & ORM Support

Prisma (Recommended)

Setup after generation:

# Generate Prisma client
npx prisma generate

# Run migrations (development)
npx prisma migrate dev

# Run migrations (production)
npx prisma migrate deploy

# Open Prisma Studio
npx prisma studio

Generated Schema (prisma/schema.prisma):

model User {
  id            String   @id @default(uuid())
  email         String   @unique
  password      String
  name          String?
  refreshToken  String?  @db.Text
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt
}

model Session {
  id        String   @id @default(uuid())
  userId    String
  token     String   @unique @db.Text
  expiresAt DateTime
  createdAt DateTime @default(now())
}

Sequelize

Notes:

  • sequelize.sync({ alter: true }) only runs in development
  • Use migrations in production
  • Models include User and Session (if auth enabled)

Production setup:

# Install Sequelize CLI
npm install -g sequelize-cli

# Run migrations
npx sequelize-cli db:migrate

Authentication System

How It Works

  1. Registration: User provides email, password, and optional name. Password is hashed with bcrypt (10 salt rounds).

  2. Login: User provides credentials. If valid, server returns:

    • accessToken (JWT, 15m expiry)
    • refreshToken (JWT, 7d expiry)
    • user object
  3. Protected Routes: Use the authenticateToken middleware:

    import { authenticateToken } from './middleware/auth';
    
    router.get('/protected', authenticateToken, (req, res) => {
      // req.userId is available here
    });
  4. Token Refresh: When access token expires, use refresh token to get a new access token.

  5. Logout: Invalidates the refresh token in the database.

Security Features

  • Passwords hashed with bcrypt
  • JWT tokens with configurable expiry
  • Refresh tokens stored in database (can be revoked)
  • HTTP-only secure cookies for sessions
  • Session store ready for user configuration (Redis/MongoDB)

Testing & Validation

Automated Tests (Run During Generation)

Test Description
Dependency Installation Runs npm install (or npm ci if lock file exists)
Prisma Setup Generates Prisma client
TypeScript Compilation Builds the project
Project Structure Validates required files exist
Docker Configuration Checks Dockerfile and docker-compose.yml
Server Smoke Test Starts server, hits /hello, verifies response, shuts down

Skip Tests

# Skip all tests
scaffjs create my-app --ts --no-install --no-test

# Skip only tests (still install)
scaffjs create my-app --ts --no-test

Verbose Output

scaffjs create my-app --ts --verbose

Shows detailed test results and performance metrics.


Production Deployment

Pre-Deployment Checklist

  1. Environment Variables: Set all secrets in .env
  2. Session Store: Configure Redis or MongoDB for sessions
  3. Database: Ensure DATABASE_URL is correct
  4. NODE_ENV: Set to production
  5. Migrations: Run npx prisma migrate deploy or Sequelize migrations

Docker Production

# Build for production
docker compose build

# Start services
docker compose up -d

# Check health
curl http://localhost:3000/health
curl http://localhost:3000/ready

Graceful Shutdown

The generated server handles:

  • SIGTERM - Kubernetes/Docker stop signal
  • SIGINT - Ctrl+C

Shutdown process:

  1. Stop accepting new connections
  2. Complete in-flight requests
  3. Close database connections
  4. Exit cleanly (or force after 30s)

Plugin System

ScaffJs supports plugins for extending functionality.

Plugin Structure

plugins/
└── my-plugin/
    ├── plugin.json          # Plugin manifest
    ├── generator.ts         # Generator function
    └── templates/           # Template files

Plugin Manifest (plugin.json)

{
  "name": "my-plugin",
  "version": "1.0.0",
  "description": "My custom plugin",
  "author": "Your Name",
  "framework": "custom",
  "generator": "./generator.ts",
  "templates": "./templates"
}

Installing Plugins

Plugins are automatically loaded from the plugins/ directory.


Troubleshooting

Port Already in Use

# Change port in .env
PORT=3001

Database Connection Failed

  1. Verify database is running
  2. Check credentials in .env
  3. Ensure correct port (PostgreSQL: 5432, MySQL: 3306)
  4. For Docker: wait for database health check

Prisma Issues

# Regenerate client
npx prisma generate

# Reset database (development only!)
npx prisma migrate reset

# Check schema validity
npx prisma validate

TypeScript Compilation Errors

# Check for errors
npm run build

# Clean and rebuild
rm -rf dist && npm run build

Docker Issues

# Rebuild images
docker compose build --no-cache

# View logs
docker compose logs -f

# Check container status
docker compose ps

Windows-Specific Issues

  • Use PowerShell or Git Bash for better compatibility
  • If cp doesn't work, use Copy-Item .env.example .env
  • For path issues, use forward slashes: src/index.ts

Project Metadata

Each generated project includes .scaffjs.json:

{
  "projectName": "my-app",
  "typescript": true,
  "auth": true,
  "database": "pg",
  "orm": "prisma",
  "docker": "dockerAll",
  "createdAt": "2024-01-01T00:00:00.000Z",
  "scaffjsVersion": "0.1.0"
}

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests
  5. Submit a pull request

See CONTRIBUTING.md for detailed guidelines.

Development Setup

git clone https://github.com/SnoWed-29/Scaff-js.git
cd Scaff-js
npm install
npm run build
npm link

# Make changes to src/
npm run build

# Test your changes
scaffjs create test-project --ts --dry-run

License

MIT License - see LICENSE for details.


Support


Built with care by the ScaffJs Team

Happy Scaffolding! 🚀

About

A scaffolding CLI that instantly generates complete, production-ready Express apps with TypeScript/JavaScript, auth, DBs, ORMs, and Docker support.

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published