npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

flenco-node-backend-cli

v0.1.12

Published

CLI tool to generate complete backend projects with Express, TypeScript, and Prisma

Readme

Flenco Node Backend CLI

A powerful CLI tool to generate production-ready Node.js backends with Express, TypeScript, and Prisma. It automatically creates CRUD operations with validation, authentication, and file upload capabilities based on your existing database schema.

NPM Downloads License TypeScript PRs Welcome Buy Me A Coffee

🚀 Features

  • 🔥 Fast project setup with step-by-step guidance
  • 📝 TypeScript support with strict mode enabled
  • 🔐 JWT Authentication with login/logout API generation
  • 📊 Prisma ORM integration with automatic client generation
  • Automatic CRUD generation for any database table
  • 📝 Request validation with Zod schemas
  • 🔄 Built-in pagination and sorting for all list endpoints
  • 🛠️ File upload support with configurable options
  • 📧 Email service integration ready to use
  • 🔍 Smart search functionality across all table fields
  • 🎯 Clean architecture with separation of concerns
  • 📚 API metadata endpoint for automatic documentation
  • 📦 Automatic Postman collection generation
  • ⚙️ User configuration system for customized experience
  • 🎨 Progress indicators and enhanced UX

📋 Prerequisites

  • Node.js >= 14 (Latest LTS recommended)
  • npm >= 6 or yarn >= 1.22
  • PostgreSQL or MySQL database
  • Basic knowledge of TypeScript and REST APIs

📦 Installation

# Install globally
npm install -g flenco-node-backend-cli

# Or using yarn
yarn global add flenco-node-backend-cli

🏃‍♂️ Quick Start

1. Initialize a New Project

# Create a new directory for your project
mkdir my-awesome-backend
cd my-awesome-backend

# Initialize the project (interactive setup)
flenco-init

The initialization process will:

  • ✅ Check your environment (Node.js version, directory status)
  • 📝 Prompt for project configuration (database, credentials)
  • 🏗️ Create project structure
  • 📦 Install dependencies automatically
  • 🔧 Generate configuration files
  • 🎯 Find available ports automatically
  • 📄 Create Postman collection for testing

2. Generate APIs for Your Tables

# Generate CRUD APIs for database tables
flenco-generate

This command will:

  • 🔍 Introspect your database schema
  • 📋 Show available tables to choose from
  • ⚙️ Ask for authentication and file upload preferences
  • 🏭 Generate complete CRUD operations
  • 🔍 Add automatic search functionality across all fields
  • 📱 Update Postman collection with new endpoints

3. Generate Authentication APIs (Optional)

During the flenco-generate process, you'll be asked:

🔐 Do you want to generate login/logout APIs? (y/N)

If you choose Yes:

  • 📋 Select the user table (users, accounts, etc.)
  • 🔑 Choose login field (email, username, mobile)
  • 🛡️ Automatic JWT token generation
  • 🚪 Login and logout endpoints created
  • 🔒 Password hashing with bcrypt

4. Refresh APIs When Schema Changes

# Update existing APIs when database schema changes
flenco-refresh

This preserves your customizations while updating:

  • 🔄 Field definitions
  • 🔍 Search capabilities
  • 📊 Validation schemas
  • 🛡️ Authentication settings

🛠️ Available Commands

| Command | Description | Usage | |---------|-------------|-------| | flenco-init | Initialize a new backend project | flenco-init | | flenco-generate | Generate APIs for database tables | flenco-generate | | flenco-refresh | Refresh APIs after schema changes | flenco-refresh | | flenco-help | Show detailed help and usage info | flenco-help | | flenco-config | Manage CLI configuration | flenco-config show | | flenco | Main command (shows options) | flenco |

⚙️ Configuration System

Customize your experience with the configuration system:

# Show current configuration
flenco-config show

# Set default database type
flenco-config set defaultDatabase postgresql

# Set default host
flenco-config set defaultHost localhost

# Skip Node.js version checks
flenco-config set skipNodeVersionCheck true

# Disable automatic dependency installation
flenco-config set autoInstallDependencies false

# Reset to defaults
flenco-config reset

Available Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | defaultDatabase | postgresql\|mysql | postgresql | Default database type | | defaultHost | string | localhost | Default database host | | defaultPort | number | 5432\|3306 | Default database port | | skipNodeVersionCheck | boolean | false | Skip Node.js version validation | | autoInstallDependencies | boolean | true | Auto-install npm packages | | generateTests | boolean | false | Generate test files (future) | | preferredCodeStyle | string | standard | Code formatting preference |

🏗️ Generated Project Structure

my-backend/
├── src/
│   ├── routes/              # API route definitions
│   │   ├── index.ts         # Main router
│   │   ├── metadata.route.ts # API documentation endpoint
│   │   ├── auth.route.ts    # Authentication routes (if generated)
│   │   └── users.route.ts   # Generated table routes
│   ├── controllers/         # Request handlers
│   │   ├── base.controller.ts
│   │   ├── auth.controller.ts
│   │   └── users.controller.ts
│   ├── services/            # Business logic layer
│   │   ├── base.service.ts
│   │   ├── auth.service.ts
│   │   └── users.service.ts
│   ├── middleware/          # Custom middleware
│   │   ├── auth.middleware.ts
│   │   ├── error.middleware.ts
│   │   ├── upload.middleware.ts
│   │   └── validate.middleware.ts
│   ├── validation/          # Zod schemas
│   │   ├── base.validation.ts
│   │   ├── common.validation.ts
│   │   ├── auth.validation.ts
│   │   └── users.validation.ts
│   ├── utils/              # Utility functions
│   │   ├── response.util.ts
│   │   ├── jwt.util.ts
│   │   ├── email.utils.ts
│   │   └── upload.util.ts
│   ├── types/              # TypeScript definitions
│   │   └── global.d.ts
│   ├── app.ts              # Express app configuration
│   └── server.ts           # Server entry point
├── prisma/                 # Database schema and migrations
│   └── schema.prisma       # Prisma schema file
├── uploads/               # File upload directory
├── api-collection.json    # Postman collection
├── .env                   # Environment variables
├── package.json           # Dependencies and scripts
└── tsconfig.json          # TypeScript configuration

🌐 Generated API Endpoints

Standard CRUD Operations

For each table (e.g., users):

| Method | Endpoint | Description | Features | |--------|----------|-------------|----------| | GET | /api/users | List all records | 📄 Pagination, 🔍 Search, 📊 Sorting | | GET | /api/users/:id | Get single record | 🎯 By ID | | POST | /api/users | Create new record | ✅ Validation, 📁 File upload | | PATCH | /api/users/:id | Update record | ✅ Partial updates | | DELETE | /api/users/:id | Delete record | 🗑️ Soft/hard delete |

Authentication Endpoints (if generated)

| Method | Endpoint | Description | |--------|----------|-------------| | POST | /api/auth/login | User login | | POST | /api/auth/logout | User logout | | POST | /api/auth/refresh | Refresh JWT token | | GET | /api/auth/profile | Get user profile |

System Endpoints

| Method | Endpoint | Description | |--------|----------|-------------| | GET | /api/metadata | API documentation | | GET | /health | Health check |

🔍 Smart Search Functionality

All list endpoints automatically support searching across all text fields in your table:

# Search across all searchable fields
GET /api/users?search=john

# Search with pagination
GET /api/users?search=admin&page=1&limit=10

# Search with sorting
GET /api/users?search=active&sortBy=createdAt&sortOrder=desc

Automatically searchable field types:

  • String fields (name, email, description, etc.)
  • Text fields
  • Varchar fields

📊 Query Parameters

All list endpoints support these query parameters:

| Parameter | Type | Default | Description | |-----------|------|---------|-------------| | page | number | 1 | Page number for pagination | | limit | number | 10 | Items per page (max 100) | | search | string | - | Search across all text fields | | sortBy | string | createdAt | Field to sort by | | sortOrder | asc\|desc | desc | Sort direction | | status | string | - | Filter by status (if field exists) |

Example Requests

# Get users with pagination
GET /api/users?page=2&limit=20

# Search for users
GET /api/users?search=john&limit=5

# Sort users by email
GET /api/users?sortBy=email&sortOrder=asc

# Complex query
GET /api/users?search=active&page=1&limit=10&sortBy=createdAt&sortOrder=desc

🔐 Authentication

JWT Token Usage

// Include in headers for protected routes
{
  "Authorization": "Bearer your-jwt-token-here"
}

Login Request Example

# Login with email
POST /api/auth/login
{
  "email": "[email protected]",
  "password": "yourpassword"
}

# Login with username
POST /api/auth/login
{
  "username": "johndoe",
  "password": "yourpassword"
}

# Login with mobile
POST /api/auth/login
{
  "mobile": "+1234567890",
  "password": "yourpassword"
}

Response Format

{
  "status": "success",
  "message": "Login successful",
  "data": {
    "user": {
      "id": 1,
      "email": "[email protected]",
      "name": "John Doe"
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expiresIn": "1d"
  }
}

📁 File Upload

Configure file uploads in your .env:

# File Upload Configuration
MAX_FILE_SIZE=5242880          # 5MB in bytes
ALLOWED_FILE_TYPES=image/jpeg,image/png,image/gif,application/pdf
UPLOAD_PATH=uploads

Upload Example

POST /api/users
Content-Type: multipart/form-data

{
  "name": "John Doe",
  "email": "[email protected]",
  "avatar": [file]  # File upload field
}

🛠️ Development Workflow

Starting Development

# Start development server with hot reload
npm run dev

# Build for production
npm run build

# Start production server
npm start

Environment Variables

Essential environment variables in .env:

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
PORT=3000

# JWT Configuration
JWT_SECRET=your-super-secret-key-change-this
JWT_EXPIRES_IN=1d

# Email Configuration (optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASS=your-app-password
[email protected]

# File Upload
MAX_FILE_SIZE=5242880
ALLOWED_FILE_TYPES=image/jpeg,image/png,image/gif
UPLOAD_PATH=uploads

# Frontend URL (for CORS and email links)
FRONTEND_URL=http://localhost:3000

📚 API Documentation

Auto-generated Documentation

Visit /api/metadata to get comprehensive API documentation including:

  • 📋 All available endpoints
  • 📝 Request/response schemas
  • 🔍 Parameter descriptions
  • 📊 Example requests

Postman Collection

Import the auto-generated api-collection.json file into Postman for:

  • 🚀 Ready-to-use requests
  • 🔧 Pre-configured environment variables
  • 📝 Request examples
  • 🧪 Testing workflows

🔧 Customization

Adding Custom Logic

// src/services/users.service.ts
export class UsersService extends BaseService {
  // Add custom methods
  async findByEmail(email: string) {
    return this.findFirst({ email });
  }

  // Override default behavior
  async create(data: any) {
    // Custom validation or processing
    const processedData = this.processUserData(data);
    return super.create(processedData);
  }
}

Custom Validation

// src/validation/users.validation.ts
export const createUserSchema = z.object({
  name: z.string().min(2).max(50),
  email: z.string().email(),
  age: z.number().min(18).max(120).optional(),
  // Add custom validation rules
});

Custom Middleware

// src/middleware/custom.middleware.ts
export const customAuthMiddleware = (req: Request, res: Response, next: NextFunction) => {
  // Custom authentication logic
  next();
};

🧪 Testing

API Testing with Postman

  1. Import api-collection.json into Postman
  2. Set environment variables:
    • baseUrl: http://localhost:3000
    • token: Your JWT token after login
  3. Test all endpoints with pre-configured requests

Manual Testing Examples

# Test user creation
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"[email protected]"}'

# Test authentication
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"password123"}'

# Test protected endpoint
curl -X GET http://localhost:3000/api/users \
  -H "Authorization: Bearer your-jwt-token"

🚀 Deployment

Environment Setup

  1. Production Environment Variables

    NODE_ENV=production
    DATABASE_URL=your-production-db-url
    JWT_SECRET=your-production-secret
    PORT=3000
  2. Build and Start

    npm run build
    npm start

Docker Deployment (Optional)

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
EXPOSE 3000
CMD ["node", "dist/server.js"]

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Development Setup

# Clone the repository
git clone https://github.com/flenco-in/flenco-node-backend-cli.git
cd flenco-node-backend-cli

# Install dependencies
npm install

# Build the project
npm run build

# Link for local testing
npm link

📋 Changelog

v0.1.11 (Latest)

  • ✅ Enhanced user experience with progress indicators
  • ✅ Added configuration system for user preferences
  • ✅ Automatic search field generation from table schema
  • ✅ Optional login/logout API generation
  • ✅ Improved error handling and validation
  • ✅ Smart port detection and project name suggestion
  • ✅ Comprehensive help system
  • ✅ Updated dependencies to latest versions

Previous Versions

❓ FAQ

Q: Can I use this with an existing database? A: Yes! The CLI works perfectly with existing databases. It will introspect your schema and generate APIs accordingly.

Q: How do I add custom validation rules? A: Edit the generated validation files in src/validation/ to add custom Zod schemas.

Q: Can I modify the generated code? A: Absolutely! The generated code is meant to be customized. Use flenco-refresh to update APIs while preserving your changes.

Q: Which databases are supported? A: Currently PostgreSQL and MySQL. Support for more databases is planned.

Q: How do I handle database migrations? A: Use Prisma migrations: npx prisma migrate dev for development and npx prisma migrate deploy for production.

🐛 Troubleshooting

Common Issues

Issue: "Command not found: flenco-init"

# Solution: Install globally or check PATH
npm install -g flenco-node-backend-cli
# or
npx flenco-node-backend-cli init

Issue: Database connection errors

# Solution: Check your DATABASE_URL in .env
# Ensure database server is running
# Verify credentials and permissions

Issue: Port already in use

# Solution: The CLI automatically finds available ports
# Or manually set PORT in .env file

Issue: TypeScript compilation errors

# Solution: Ensure dependencies are installed
npm install
npm run build

For more issues, visit our GitHub Issues page.

📞 Support

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments


Made with ❤️ by Atish Paul

Star ⭐ this repository if it helped you build amazing backends faster!