Node APIs Generator
π The most advanced TypeScript API generator for Node.js - Create production-ready API modules with clean architecture, comprehensive testing, and automatic code formatting.
β¨ Why Choose Node APIs Generator?
- π Object Destructuring - Modern TypeScript patterns with clean parameter handling
- π§ Intelligent Validation - Automatic Zod schema generation with pattern recognition
- π Named Fields - Production-ready default fields instead of empty placeholders
- ποΈ Clean Architecture - Controller β Handler β Repository pattern
- π Multi-Framework - Support for Express.js and Hono frameworks
- π¨ Smart Naming - Accepts any naming format, generates consistent professional code
- β‘ Performance Monitoring - Built-in execution timing and request correlation
- π Request Tracing - Complete payload logging for easy debugging
- π― Type-Driven - Intelligent code generation from TypeScript types
- π§ TypeScript Strict Mode - Generated code passes strict TypeScript compilation
- π¦ Dependency-Free - Generated repositories have zero external dependencies
- β¨ Auto-Formatting - Prettier integration for consistent code style
- π Two-Phase Generation - Review types first, then generate code with optimized folder structures
- π― Smart Interactive Mode - Numbered selection, validation, and existing module handling
- π§ͺ Comprehensive Testing - Complete integration test suite generated automatically
- π‘οΈ Production Ready - Error handling, validation, and observability built-in
- π« No Service Layer - Direct handler-to-repository pattern for simplicity
- βοΈ Smart Configuration - Set preferences once, skip repetitive prompts
- π¦ Zero Config - Works out of the box with sensible defaults
π Try It Now!
# Install globally and start building amazing APIs
npm install -g node-apis
# Generate REST APIs
node-apis --name blog --crud --api-style rest --framework express
# Generate tRPC APIs
node-apis --name user --crud --api-style trpc --framework hono
# Run the comprehensive tests
npm test
β Love this tool? Star it on GitHub and follow @sobebarali for more developer tools!
π― What Makes This Different?
Unlike other generators that create static boilerplate, this tool:
- Uses modern TypeScript patterns with object destructuring and intelligent type inference
- Generates smart validation with automatic Zod schema creation and pattern recognition
- Provides production-ready templates with realistic named fields instead of empty placeholders
- Parses your TypeScript types and generates intelligent code
- Includes performance monitoring and request correlation out of the box
- Follows modern clean architecture patterns
- Generates working, formatted code that's ready for production
- Creates comprehensive test suites with integration tests
- Supports iterative development with smart type-driven regeneration
π¨ Smart Naming System
The generator accepts any naming format and automatically converts it to professional, consistent naming conventions:
Input Format | Directory | Files | Classes | Variables | Constants |
---|---|---|---|---|---|
user-profile |
user-profile/ |
create.userProfile.ts |
CreateUserProfile |
userProfile |
USER_PROFILE |
blog_post |
blog-post/ |
create.blogPost.ts |
CreateBlogPost |
blogPost |
BLOG_POST |
productCategory |
product-category/ |
create.productCategory.ts |
CreateProductCategory |
productCategory |
PRODUCT_CATEGORY |
OrderHistory |
order-history/ |
create.orderHistory.ts |
CreateOrderHistory |
orderHistory |
ORDER_HISTORY |
Benefits:
- β Flexible Input - Use any naming style you prefer
- β Valid JavaScript - All generated identifiers are syntactically correct
- β Professional Output - Follows industry-standard naming conventions
- β Import Safety - No path mismatches or file not found errors
π¨ Choose Your API Style
The generator supports two distinct API paradigms, each optimized for different use cases:
π REST APIs (Traditional HTTP)
- Best for: Public APIs, microservices, traditional web applications
- Generates: Controllers, routes, HTTP endpoints with Express/Hono
- Benefits: Standard HTTP patterns, widely adopted, framework agnostic
π tRPC APIs (Type-safe RPC)
- Best for: Full-stack TypeScript applications, internal APIs, type-safe client-server communication
- Generates: Procedures, routers, end-to-end type safety
- Benefits: Auto-completion, compile-time safety, seamless TypeScript integration
Interactive Flow:
π Which API style would you like to generate?
π REST APIs (traditional HTTP endpoints)
π tRPC (type-safe RPC procedures)
π οΈ Which web framework would you like to use?
Express.js (Traditional, widely adopted)
Hono (Modern, lightweight, fast)
π Quick Start
Installation
# Global installation (recommended)
npm install -g node-apis
# Or use npx (no installation required)
npx node-apis
First-Time Setup (Optional)
Set your framework preference to skip repetitive prompts:
# Interactive setup - choose your preferred framework
node-apis --init-config
# Or set directly
node-apis --set-framework hono # or express
π¨ Monorepo Users - Important Note
If you're working in a monorepo (pnpm workspaces, Yarn workspaces, npm workspaces) and encounter this error:
npm error Unsupported URL Type "workspace:": workspace:*
Solution: Use global installation to avoid workspace conflicts:
# β
Recommended: Install globally
npm install -g node-apis
# β
Alternative: Use npx (no installation)
npx node-apis
# β
pnpm users: Bypass workspace
pnpm add -g node-apis
# β
Yarn users: Global install
yarn global add node-apis
Why this happens: Monorepos use workspace:
protocol for local packages, which can conflict with npm registry installations. Global installation bypasses workspace resolution.
Generate Your First API
# Interactive mode - just run the command!
node-apis
# Or specify directly - any naming format works!
node-apis --name user-profile --crud
node-apis --name blog_post --crud
node-apis --name productCategory --crud
# Choose your framework
node-apis --name book --crud --framework express # Default
node-apis --name book --crud --framework hono # Lightweight alternative
π― Three API Types
The generator supports three distinct API types with optimized folder structures:
1. CRUD APIs (--crud
)
Full-stack database operations with HTTP endpoints:
- Use for: User management, product catalogs, blog posts
- Generates: Controllers, handlers, repository, validators, routes, tests
- Pattern: HTTP β Controller β Handler β Repository β Database
- Folders:
controllers/
,handlers/
,repository/
,services/
,types/
,validators/
,routes
2. Custom APIs (--custom
)
Business logic operations with HTTP endpoints:
- Use for: Authentication, notifications, file uploads
- Generates: Controllers, services, validators, routes, tests
- Pattern: HTTP β Controller β Service β External APIs/Logic
- Folders:
controllers/
,handlers/
,repository/
,services/
,types/
,validators/
,routes
3. Internal Services (--services
) β Optimized Structure
Third-party integrations for internal use (no HTTP layer):
- Use for: Payment processing, email services, cloud APIs
- Generates: Pure service functions, types, comprehensive tests
- Pattern: Direct function calls β External APIs
- Folders: Only
services/
andtypes/
(clean & minimal) - Import: Use in other modules via
import { serviceFunction } from '../module/services/...'
π New in v3.5.0: Intelligent Code Generation
π§ Smart Object Destructuring
Handlers now use modern TypeScript patterns with clean parameter destructuring:
// β¨ Generated handler with object destructuring
export default async function createProductHandler({
name,
description,
status,
requestId,
}: {
name: string;
description: string;
status: string;
requestId: string;
}): Promise<typeResult> {
const product = await create({ name, description, status });
// ...
}
π― Automatic Validation Generation
Smart Zod schema generation with pattern recognition:
// β¨ Generated validator with intelligent patterns
export const payloadSchema = z.object({
name: z.string(),
userEmail: z.string().email().optional(), // π― Auto-detected email
userId: z.string().uuid(), // π― Auto-detected UUID
phoneNumber: z.string().min(10), // π― Auto-detected phone
profileUrl: z.string().url().optional(), // π― Auto-detected URL
description: z.string().optional(),
});
π Production-Ready Named Fields
No more empty placeholders - every module generates with realistic, useful fields:
// β¨ Generated types with meaningful fields
export type typePayload = {
name: string; // Universal title/label field
description?: string; // Common descriptive field
status?: string; // Useful for state management
// Add more fields here
};
// β¨ Module-specific IDs
export type typeResultData = {
productId: string; // Smart ID naming
name: string;
description: string | null;
status: string | null;
created_at: string;
updated_at: string;
};
π Type-Driven Intelligence
The generator analyzes your TypeScript types and generates intelligent code:
- Smart ID Detection: Automatically uses
todoId
,userId
,productId
instead of genericid
- Optional Field Handling: Proper handling in UPDATE operations (partial updates)
- Pattern Recognition: Field names trigger appropriate validation (email, URL, phone, UUID)
- Framework Adaptation: Same intelligent patterns work for both Express.js and Hono
βοΈ Configuration
Set your preferences once and skip repetitive prompts:
# Initialize configuration (interactive)
node-apis --init-config
# Set default framework and API style
node-apis --set-framework express
node-apis --set-api-style trpc
# Now generate without specifying preferences
node-apis --name user --crud # Uses your configured framework and API style
The config file (node-apis.config.json
) stores your preferences and is extensible for future features like database ORM selection.
Configuration Workflow Example
# First time setup - choose your preferences interactively
node-apis --init-config
# β
Configuration file created successfully!
# π Default framework: express, API style: rest
# Change preferences anytime
node-apis --set-framework hono
node-apis --set-api-style trpc
# β
Framework set to: hono
# β
API style set to: tRPC procedures
# Now generate APIs without specifying preferences
node-apis --name user --crud
# Uses Hono + tRPC from config
# Override config for specific generation
node-apis --name admin --crud --api-style rest --framework express
# Uses Express + REST despite Hono + tRPC being configured
π’ Monorepo Support
Working in a monorepo? The CLI supports custom target directories so you can generate APIs from any location:
Option 1: Use --target-dir
Flag
Generate APIs directly from your monorepo root:
# From monorepo root, generate in apps/server/
node-apis --name user --crud --target-dir apps/server
# From monorepo root, generate in packages/api/
node-apis --name product --crud --target-dir packages/api
# Target directory can be absolute or relative
node-apis --name order --crud --target-dir /path/to/your/backend
Option 2: Global Installation
Install globally to avoid workspace protocol errors:
# β
Recommended for monorepos
npm install -g node-apis
# Use from anywhere in your monorepo
cd monorepo-root
node-apis --name user --crud --target-dir apps/api
Option 3: Use npx
Run without installation:
# Always works, no conflicts
npx node-apis --name user --crud --target-dir apps/server
Monorepo Examples
# Nx monorepo
node-apis --name auth --crud --target-dir apps/backend
# Lerna/Rush monorepo
node-apis --name user --crud --target-dir packages/api
# Yarn/pnpm workspaces
node-apis --name product --crud --target-dir services/catalog-api
# Custom structure
node-apis --name notification --services --target-dir infrastructure/email-service
The generated structure will be:
your-target-dir/
βββ src/apis/your-module/
βββ controllers/
βββ handlers/
βββ ...
π‘ Pro Tip: Use global installation (
npm install -g node-apis
) to avoid workspace conflicts and enable usage from any directory.
That's it! You'll get a complete, production-ready API module with:
- β Controllers with request logging
- β Handlers with performance monitoring
- β Repository with clean data access
- β TypeScript types and validation
- β Comprehensive integration test suite
- β Test configuration (Vitest + Supertest)
- β Automatic code formatting
ποΈ Generated Architecture
Your APIs follow a clean, modern architecture with smart naming and comprehensive testing:
src/apis/user-profile/ # kebab-case directories
βββ controllers/ # HTTP routing with payload logging
β βββ create.userProfile.ts # camelCase files β POST /api/user-profiles
β βββ get.userProfile.ts # GET /api/user-profiles/:id
β βββ list.userProfile.ts # GET /api/user-profiles
β βββ update.userProfile.ts # PUT /api/user-profiles/:id
β βββ delete.userProfile.ts # DELETE /api/user-profiles/:id
βββ handlers/ # Business logic with performance monitoring
β βββ create.userProfile.ts # β
Execution timing
β βββ get.userProfile.ts # β
Error handling
β βββ ... # β
Request correlation
βββ repository/ # Data access layer
β βββ user-profile.repository.ts # β
Clean functions
βββ types/ # TypeScript definitions
β βββ create.userProfile.ts # β
Type-safe payloads
β βββ ... # β
Result types
βββ validators/ # Zod validation schemas
β βββ create.userProfile.ts # β
Input validation
β βββ ... # β
Error handling
βββ user-profile.routes.ts # Express/Hono router
tests/user-profile/ # Comprehensive test suite
βββ create/
β βββ validation.test.ts # Input validation tests
β βββ success.test.ts # Happy path integration tests
β βββ errors.test.ts # Error handling tests
βββ get/
β βββ ... (same pattern for all operations)
βββ shared/
βββ helpers.ts # Test utilities
π‘ Improved Two-Phase Generation Process
Phase 1: Type Definition & Review
node-apis --name book --crud
# π Phase 1: Generating directory structure and type files...
# β
Type files generated successfully!
What happens:
- Creates main module directory and
types/
subdirectory only - Generates TypeScript type files with placeholder interfaces
- Shows detailed instructions for each operation type
- Prompts you to review and customize the
typePayload
interfaces
Example type file generated:
export type typePayload = {
// Add your specific fields here
// name: string;
// description: string;
// category?: string;
};
Phase 2: Code Generation & Testing
# After you review types and confirm (type 'yes' or 'y')
# π Phase 2: Generating services and repositories...
# π§ͺ Phase 3: Generating comprehensive test suite...
What happens:
- Creates remaining directories based on API type:
- Services: Only
services/
(no HTTP layer) - CRUD/Custom: All folders (controllers, handlers, repository, validators, routes)
- Services: Only
- Generates all code files using your confirmed type definitions
- Auto-formats all generated code with Prettier
- Creates comprehensive test suite with validation, success, and error cases
Benefits of Two-Phase Approach
- π― Type-First Development: Define your data structures before implementation
- π§ Customizable: Edit types to match your exact requirements
- π« No Rework: Generated code uses your confirmed field definitions
- π Clean Structure: Services get minimal folders, APIs get full structure
- β‘ Efficient: Only creates what each API type actually needs
π₯ Generated Code Examples
Controller (HTTP Layer) - Smart Naming in Action
// Input: --name user-profile
// Generated: src/apis/user-profile/controllers/create.userProfile.ts
import { validatePayload } from '../validators/create.userProfile';
import createUserProfileHandler from '../handlers/create.userProfile';
export default async function createUserProfileController(
req: Request,
res: Response
): Promise<void> {
const requestId = (req.headers['x-request-id'] as string) || generateRequestId();
// Professional naming: USER_PROFILE (CONSTANT_CASE)
console.info(
`${requestId} [CONTROLLER] - CREATE USER_PROFILE payload:`,
JSON.stringify(req.body, null, 2)
);
// Validation with detailed error responses
const validation = validatePayload(req.body);
if (!validation.success) {
res.status(400).json({
data: null,
error: { code: 'VALIDATION_ERROR', message: validation.error.message, statusCode: 400 },
});
return;
}
// Call handler with request correlation - PascalCase function names
const result = await createUserProfileHandler(validation.data, requestId);
const statusCode = result.error ? result.error.statusCode : 201;
res.status(statusCode).json(result);
}
Handler (Business Logic) - TypeScript Best Practices
// TypeScript best practice: import type for type-only imports
import type {
typePayload,
typeResult,
typeResultData,
typeResultError,
} from '../types/create.userProfile';
import create from '../repository/user-profile.repository';
export default async function createUserProfileHandler(
payload: typePayload,
requestId: string
): Promise<typeResult> {
let data: typeResultData | null = null;
let error: typeResultError | null = null;
try {
const startTime = Date.now();
console.info(`${requestId} [USER_PROFILE] - CREATE handler started`);
// Direct repository call (no service layer)
const userProfile = await create(payload);
data = userProfile;
const duration = Date.now() - startTime;
console.info(
`${requestId} [USER_PROFILE] - CREATE handler completed successfully in ${duration}ms`
);
} catch (err) {
// TypeScript strict mode compatible error handling
const errorMessage = err instanceof Error ? err.message : 'An unexpected error occurred';
console.error(`${requestId} [USER_PROFILE] - CREATE handler error: ${errorMessage}`);
error = {
code: 'CREATE_FAILED',
message: errorMessage,
statusCode: 500,
};
}
return { data, error };
}
Repository (Data Access) - Dependency-Free & Type-Safe
// TypeScript best practice: import type for type-only imports
import type { typePayload as CreatePayload } from '../types/create.userProfile';
export default async function create(payload: CreatePayload) {
try {
// TODO: Replace with your database implementation
// Example: return await db.userProfile.create({ data: payload });
// Mock implementation - replace with actual database call
const userProfile = {
id: `mock-id-${Date.now()}`,
...payload,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
return userProfile;
} catch (error) {
// TypeScript strict mode compatible - no custom error classes needed
throw new Error(
`Database error: Failed to create user profile: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
// β
No external dependencies - completely self-contained
// β
Uses native Error class instead of custom error classes
// β
TypeScript strict mode compatible
// β
Valid JavaScript identifiers (camelCase variables)
π§ͺ Generated Test Suite
Integration Tests (Focus on Real API Testing)
// tests/book/create-book/success.test.ts
import { describe, it, expect } from 'vitest';
import request from 'supertest';
import app from '../../../src/app';
import { typePayload } from '../../../src/apis/book/types/create.book';
describe('Create Book - Success Tests', () => {
it('should create book successfully', async () => {
const payload: typePayload = {
title: 'Test Book',
author: 'Test Author',
metadata: { publisher: 'Test Publisher' },
};
const response = await request(app).post('/api/books').send(payload).expect(201);
expect(response.body.data).toBeDefined();
expect(response.body.error).toBeNull();
});
});
Error Handling Tests
// tests/book/create-book/errors.test.ts
describe('Create Book - Error Tests', () => {
it('should return 400 for invalid payload', async () => {
const invalidPayload = { invalidField: 'invalid-value' };
const response = await request(app).post('/api/books').send(invalidPayload).expect(400);
expect(response.body.data).toBeNull();
expect(response.body.error.code).toBe('VALIDATION_ERROR');
});
});
Validation Tests
// tests/book/create-book/validation.test.ts
describe('Create Book - Validation Tests', () => {
it('should validate required fields', () => {
const payload: typePayload = {
title: 'Valid Book',
author: 'Valid Author',
metadata: { publisher: 'Valid Publisher' },
};
const result = validatePayload(payload);
expect(result.success).toBe(true);
});
});
π― Usage Examples
Basic CRUD API with Smart Naming
# Any naming format works - the generator handles it intelligently!
node-apis --name user-profile --crud # kebab-case
node-apis --name blog_post --crud # snake_case
node-apis --name productCategory --crud # camelCase
node-apis --name OrderHistory --crud # PascalCase
# All generate professional, consistent code:
# β
5 endpoints: POST, GET, GET/:id, PUT/:id, DELETE/:id
# β
Complete TypeScript types with proper naming
# β
Zod validation schemas
# β
15 integration tests (3 per operation)
# β
Test configuration (Vitest + Supertest)
# β
Performance monitoring
# β
Request correlation
# β
Auto-formatted code
Multi-Framework Support
# Express.js (default)
node-apis --name user-profile --crud --framework express
# Hono (lightweight alternative)
node-apis --name blog_post --crud --framework hono
# Both generate framework-specific code with consistent naming!
Custom Operations with Tests
# Generate custom user operations
node-apis --name user --custom "login,logout,resetPassword"
# What you get:
# β
3 custom endpoints with full implementation
# β
Type-safe request/response interfaces
# β
Validation schemas
# β
9 integration tests (3 per operation)
# β
Error handling tests
# β
Validation tests
Internal Service Operations
# Generate third-party service integrations
node-apis --name stripe --services "createPayment,refund,getPaymentStatus"
node-apis --name sendgrid --services "sendEmail,sendBulkEmail"
# What you get:
# β
Pure service functions (no HTTP layer)
# β
Clean folder structure (only services/ and types/)
# β
Type-safe request/response interfaces
# β
Error handling with consistent patterns
# β
Comprehensive test suites (validation, success, error cases)
# β
Ready for internal use in other modules
# β
Template code with TODO comments for easy implementation
Generated Structure for Services:
src/apis/stripe/
βββ services/
β βββ createPayment.stripe.ts
β βββ refund.stripe.ts
β βββ getPaymentStatus.stripe.ts
βββ types/
βββ createPayment.stripe.ts
βββ refund.stripe.ts
βββ getPaymentStatus.stripe.ts
# No controllers/, handlers/, validators/, repository/ folders
# Services are pure functions for internal use
Interactive Mode (Recommended) β
# Just run the command - it's smart and user-friendly!
node-apis
# π― Smart Features:
# β
Numbered selection (works in all terminals)
# β
Existing module detection with smart options
# β
Enhanced validation with helpful examples
# β
Clear visual feedback with emojis and formatting
# π Interactive Flow:
# 1. π Detect existing modules (if any)
# 2. π Enter module name with validation
# 3. π― Choose API type (1-3 numbered selection):
# 1. ποΈ CRUD operations (Create, Read, Update, Delete)
# 2. β‘ Custom API operations (Business logic endpoints)
# 3. π§ Internal service operations (Third-party integrations)
# 4. π Enter operation names with smart validation
# 5. π Choose API style (REST or tRPC) - NEW!
# 6. βοΈ Framework selection (Express or Hono)
# 7. π¨ Handle existing modules:
# β’ π Overwrite existing module (replace all files)
# β’ β Add operations to existing module
# β’ β Cancel generation
# 8. β¨ Two-phase generation with type review
# 9. π§ͺ Comprehensive test suite generation
π― Interactive Mode Benefits
- Terminal Compatible: Numbered selection works everywhere
- Smart Validation: Helpful examples and error messages
- Existing Module Handling: Never accidentally overwrite work
- Visual Feedback: Emojis and clear formatting
- Type-First: Review and customize types before code generation
Type-Driven Development with Smart Naming
# 1. Generate types first (any naming format!)
node-apis --name product_category --crud
# 2. Edit the types (add your fields)
# Edit: src/apis/product-category/types/create.productCategory.ts
# 3. Code and tests automatically use your exact types!
# All generated code is type-safe and uses consistent naming:
# - Directory: product-category/ (kebab-case)
# - Files: create.productCategory.ts (camelCase)
# - Classes: CreateProductCategoryController (PascalCase)
# - Variables: productCategory (camelCase)
# - Constants: PRODUCT_CATEGORY (CONSTANT_CASE)
Run Your Tests
# Run all tests
npm test
# Run tests for specific module
npm run test:module -- product
# Run with coverage
npm run test:coverage
# Watch mode for development
npm run test:watch
π₯ tRPC Support - Type-Safe APIs Made Easy
New in v3.6.1: Enhanced tRPC procedures with consistent error handling and improved type safety!
π― What is tRPC Style?
tRPC (TypeScript Remote Procedure Call) provides end-to-end type safety from your backend to frontend. Instead of traditional REST endpoints, you get type-safe procedure calls with automatic validation.
π Quick tRPC Example
# Generate tRPC procedures instead of REST controllers
node-apis --name blog --crud --trpc-style
# Set tRPC as your default style
node-apis --set-trpc-style true
node-apis --name user --crud # Uses tRPC style
ποΈ tRPC vs REST Structure Comparison
tRPC Style | REST Style |
---|---|
src/apis/blog/ |
src/apis/blog/ |
βββ procedures/ |
βββ controllers/ |
βββ handlers/ |
βββ handlers/ |
βββ repository/ |
βββ repository/ |
βββ types/ |
βββ types/ |
βββ validators/ |
βββ validators/ |
βββ blog.router.ts |
βββ blog.routes.ts |
π― Generated tRPC Code Examples
tRPC Procedure (procedures/create.blog.ts
)
import { publicProcedure } from '../../../trpc';
import { payloadSchema } from '../validators/create.blog';
import createBlogHandler from '../handlers/create.blog';
import type { typePayload } from '../types/create.blog';
export const createBlogProcedure = publicProcedure
.input(payloadSchema) // π― Automatic validation
.mutation(async ({ input }: { input: typePayload }) => { // π― Enhanced type safety
const requestId = generateRequestId();
try {
return await createBlogHandler({ // π― Same business logic
...input,
requestId,
});
} catch (error) { // π‘οΈ Consistent error handling
return {
data: null,
error: {
code: 'INTERNAL_ERROR',
message: error instanceof Error ? error.message : 'Something went wrong',
statusCode: 500,
requestId
}
};
}
});
tRPC Router (blog.router.ts
)
import { router } from '../../trpc';
import { createBlogProcedure } from './procedures/create.blog';
import { getBlogProcedure } from './procedures/get.blog';
// ...
export const blogRouter = router({
create: createBlogProcedure, // π― Procedure mapping
get: getBlogProcedure,
list: listBlogsProcedure,
update: updateBlogProcedure,
delete: deleteBlogProcedure,
});
export type BlogRouter = typeof blogRouter; // π― Type export
π§ Required tRPC Setup
To use the generated tRPC code, you'll need to set up tRPC in your project:
1. Install Dependencies
npm install @trpc/server @trpc/client zod
2. Create tRPC Setup (src/trpc/index.ts
)
import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
export const router = t.router;
export const publicProcedure = t.procedure;
// Main app router
import { blogRouter } from '../apis/blog/blog.router';
export const appRouter = router({
blog: blogRouter,
// Add more modules here
});
export type AppRouter = typeof appRouter;
3. Express Integration (src/server.ts
)
import express from 'express';
import { createExpressMiddleware } from '@trpc/server/adapters/express';
import { appRouter } from './trpc';
const app = express();
app.use(
'/trpc',
createExpressMiddleware({
router: appRouter,
})
);
app.listen(3000);
π Client Usage Examples
Next.js Client
import { createTRPCNext } from '@trpc/next';
import type { AppRouter } from '../server/trpc';
export const trpc = createTRPCNext<AppRouter>({
config() {
return { url: '/api/trpc' };
},
});
// In a React component
function BlogManager() {
const createBlog = trpc.blog.create.useMutation();
const { data: blogs } = trpc.blog.list.useQuery({ page: 1 });
const handleCreate = async () => {
const result = await createBlog.mutateAsync({
name: 'My Blog Post', // β
Type-safe
description: 'Great post!', // β
Auto-complete
status: 'published', // β
Validated
});
if (result.data) {
console.log('Created:', result.data.blogId); // β
Type inference
}
};
return (
<div>
<button onClick={handleCreate}>Create Blog</button>
{blogs?.data?.items.map(blog => (
<div key={blog.blogId}>{blog.name}</div>
))}
</div>
);
}
π― Key Benefits of tRPC Style
β End-to-End Type Safety
// Full TypeScript inference
const blog = await trpc.blog.create.mutate({
name: "Post Title", // β
Type-safe
description: "Content", // β
Optional field
// status: 123 // β TypeScript error!
});
// Automatic return type inference
blog.data?.blogId; // β
string
blog.data?.created_at; // β
string
β Enhanced Error Handling (New in v3.6.1)
// Consistent error format across all procedures
const result = await trpc.blog.create.mutate({ name: "Test" });
if (result.error) {
console.log(result.error.code); // β
'INTERNAL_ERROR'
console.log(result.error.message); // β
Descriptive error message
console.log(result.error.statusCode); // β
HTTP status code
console.log(result.error.requestId); // β
Request tracing ID
}
β Same Business Logic
The handlers, repository, and types are identical to REST - only the transport layer changes!
β Smart Validation
// Automatic Zod validation
trpc.blog.create.mutate({
name: "", // β Validation error
description: null, // β Type error
});
β Performance Benefits
- Direct procedure calls (no HTTP overhead)
- Built-in caching with React Query
- Automatic request deduplication
- Optimistic updates support
π― When to Use Each Style
Use tRPC Style When:
- β Full-stack TypeScript projects
- β Team values type safety
- β Modern development workflow
- β React/Next.js frontend
- β API consumed primarily by your own frontend
Use REST Style When:
- β Public APIs for third parties
- β Multiple different client technologies
- β Traditional HTTP/JSON APIs
- β OpenAPI/Swagger documentation needed
π tRPC Configuration
Set tRPC as your default style:
# Set tRPC style preference
node-apis --set-trpc-style true
# Now all generations use tRPC style by default
node-apis --name user --crud # Uses tRPC procedures
node-apis --name auth --custom "login,logout" # Uses tRPC procedures
# Override for specific generation
node-apis --name public-api --crud --framework express # Uses REST despite tRPC config
π₯ Complete tRPC Example
Generate a complete blog API with tRPC:
# Generate blog API with tRPC style (new syntax)
node-apis --name blog --crud --api-style trpc --framework express
# Or using deprecated syntax (shows warning)
node-apis --name blog --crud --trpc-style
# What you get:
# β
5 tRPC procedures (create, get, list, update, delete)
# β
Type-safe validation with Zod schemas
# β
Business logic handlers with object destructuring
# β
Repository functions for data access
# β
TypeScript types for requests/responses
# β
Complete test suite for all operations
# β
tRPC router combining all procedures
# β
Production-ready code with error handling
Generated structure:
src/apis/blog/
βββ procedures/ # π tRPC procedures
β βββ create.blog.ts
β βββ get.blog.ts
β βββ ...
βββ handlers/ # β
Same business logic
βββ repository/ # β
Same data access
βββ types/ # β
Same TypeScript types
βββ validators/ # β
Same Zod schemas (perfect for tRPC!)
βββ blog.router.ts # π tRPC router
This is a complete, production-ready tRPC API generated in seconds! π
π Command Line Options
Option | Alias | Description |
---|---|---|
--name <name> |
-n |
Module name (skips interactive prompt) |
--crud |
| Generate CRUD operations (create, get, list, update, delete) | |
--custom <names> |
| Generate custom operations (comma-separated) | |
--services <names> |
| Generate internal service operations (comma-separated) | |
--api-style <style> |
| API style to generate (rest|trpc), defaults to rest π | |
--framework <framework> |
| Web framework to use (express|hono), defaults to express | |
--target-dir <dir> |
| Target directory for generated files (default: current directory) | |
--set-api-style <style> |
| Set default API style in config (rest|trpc) π | |
--set-framework <framework> |
| Set default framework in config (express|hono) | |
--trpc-style |
| β οΈ Deprecated: Use --api-style trpc instead |
|
--set-trpc-style <bool> |
| β οΈ Deprecated: Use --set-api-style instead |
|
--force |
-f |
Overwrite existing files |
--no-interactive |
| Skip interactive prompts | |
--init-config |
| Initialize configuration file | |
--version |
-V |
Show version number |
--help |
-h |
Show help information |
π¨ What Makes the Generated Code Special?
β Performance Monitoring Built-In
req-1703123456789-abc123 [BOOK] - CREATE handler started
req-1703123456789-abc123 [BOOK] - CREATE handler completed successfully in 45ms
β Complete Request Tracing
req-1703123456789-abc123 [CONTROLLER] - CREATE BOOK payload: {
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
}
β Production-Ready Error Handling
{
"data": null,
"error": {
"code": "VALIDATION_ERROR",
"message": "Title is required",
"statusCode": 400
}
}
β Type-Safe Throughout
- Controllers know exact request/response types
- Handlers use your custom field definitions
- Repositories match your data structure
- Validators enforce your business rules
π‘οΈ Production-Ready Error Handling
Defense in Depth Architecture (New in v3.6.1)
The generator now implements comprehensive error handling across all API layers, ensuring your applications are resilient and production-ready:
Complete Coverage Across All Layers
π API Entry Points
βββ π‘οΈ Controllers (Express/Hono) - Framework & validation errors
βββ π‘οΈ tRPC Procedures - Procedure-level errors (NEW!)
βββ π‘οΈ Handlers - Business logic errors
βββ π‘οΈ Repository - Data access errors
Consistent Error Format
All layers return the same standardized error structure:
{
data: null,
error: {
code: 'VALIDATION_ERROR' | 'NOT_FOUND' | 'INTERNAL_ERROR',
message: 'Descriptive error message',
statusCode: 400 | 404 | 500,
requestId: 'req-abc123...' // For request tracing
}
}
Enhanced tRPC Error Handling
// Every tRPC procedure now includes robust error handling
export const createUserProcedure = publicProcedure
.input(payloadSchema)
.mutation(async ({ input }: { input: typePayload }) => {
const requestId = randomBytes(16).toString('hex');
try {
return await createUserHandler({ ...input, requestId });
} catch (error) {
// Consistent error format with request tracing
return {
data: null,
error: {
code: 'INTERNAL_ERROR',
message: error instanceof Error ? error.message : 'Something went wrong',
statusCode: 500,
requestId // Essential for debugging
}
};
}
});
Benefits of This Approach
- π Request Tracing: Every error includes a
requestId
for debugging - π Consistency: Same error format across Express, Hono, and tRPC
- π‘οΈ Reliability: Prevents unhandled promise rejections
- π Monitoring: Structured errors perfect for logging systems
- π― Production Ready: Built for real-world application requirements
π Advanced Features
Smart Type-Driven Generation
- Parses your TypeScript types and generates matching code
- Regenerates handlers when you update type definitions
- Maintains consistency between types and implementation
- Tests automatically use your exact types for complete type safety
Comprehensive Testing
- Integration tests only - focus on real API behavior
- No complex mocking - tests actual endpoints with supertest
- Type-safe tests - all tests use your TypeScript types
- Complete coverage - validation, success, and error scenarios
- Ready-to-run - includes Vitest configuration and scripts
Automatic Code Formatting
- Prettier integration formats all generated code
- Consistent style across your entire codebase
- No manual formatting needed
Clean Architecture
- No service layer bloat - direct handler-to-repository pattern
- Single responsibility - each layer has a clear purpose
- Easy to test - clean separation of concerns
- Performance monitoring built into every handler
Developer Experience
- Interactive CLI that guides you through the process
- Smart defaults that work out of the box
- Incremental development - add operations to existing modules
- Type safety throughout the entire stack
- Test-driven development ready out of the box
π¦ Requirements
- Node.js >= 16.0.0
- TypeScript project (the generator creates TypeScript files)
π§ Troubleshooting
Common Issues and Solutions
π¨ Workspace Protocol Error (Monorepo Users)
npm error Unsupported URL Type "workspace:": workspace:*
Solution: Install globally to avoid workspace conflicts:
npm install -g node-apis # β
Recommended
# or
npx node-apis # β
No installation needed
π¨ Permission Denied (macOS/Linux)
Error: EACCES: permission denied
Solution: Use sudo or fix npm permissions:
sudo npm install -g node-apis # Quick fix
# or
npm config set prefix ~/.npm-global # Better long-term solution
π¨ Command Not Found After Global Install
bash: node-apis: command not found
Solution: Check your PATH or use npx:
npx node-apis # Always works
# or
echo $PATH # Check if npm global bin is in PATH
π¨ TypeScript Compilation Errors in Generated Code
Solution: Ensure you have TypeScript installed and compatible version:
npm install -g typescript # Global TypeScript
# or in your project
npm install --save-dev typescript
Note: Generated code is compatible with TypeScript strict mode and follows best practices:
- Uses
import type
for type-only imports - Proper error handling with
instanceof Error
checks - Valid JavaScript identifiers for all variable names
π¨ Tests Failing After Generation
Solution: Install test dependencies:
npm install --save-dev vitest supertest @types/supertest
π‘ Pro Tips
- Always use global installation for CLI tools like
node-apis
- Use npx if you prefer not to install globally
- Check the generated files - they include helpful TODO comments
- Customize the types first before generating the full code
- Generated code is TypeScript strict mode ready - no compilation errors
- No external dependencies - generated repositories are completely self-contained
- Use any naming format - the smart naming system handles everything
π€ Contributing
We welcome contributions! Here's how:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
π Changelog
v3.6.1 - Enhanced Error Handling & Type Safety π‘οΈ
π₯ Major Enhancement: Consistent Error Handling
- β Enhanced tRPC Procedures: Added try-catch blocks to all tRPC procedure templates
- β
Type Safety Improvements: Explicit
typePayload
typing in all procedures - β Consistent Error Format: All procedures return standardized error structure
- β Defense in Depth: Complete error handling coverage across all API layers
- β Request Tracing: Request IDs included in all error responses for debugging
- β Production Ready: Prevents unhandled promise rejections and crashes
v3.5.1 - tRPC Integration & Monorepo Support π
π₯ Major Feature: tRPC Support
- β tRPC Style Generation: Generate tRPC procedures instead of REST controllers
- β Type-Safe APIs: Full end-to-end type safety from backend to frontend
- β
CLI Integration:
--trpc-style
flag and--set-trpc-style
configuration - β Smart Templates: New tRPC procedure, router, and test templates
- β Same Business Logic: Reuses existing handlers, repository, types, and validators
- β Conditional Generation: Switch between tRPC and REST styles seamlessly
π’ Monorepo Support
- β
Target Directory:
--target-dir
flag for generating in specific directories - β Flexible Paths: Support for absolute and relative target paths
- β Root Generation: Generate APIs from monorepo root without cd commands
- β Global Installation: Improved compatibility with workspace protocols
π― Enhanced Developer Experience
- β Interactive tRPC Setup: Prompts for setting tRPC style preference
- β Configuration Management: Persistent tRPC style settings in config file
- β Comprehensive Documentation: Complete tRPC setup and usage examples
- β Performance Benefits: Direct procedure calls with built-in validation
v3.5.0 - Major Code Generation Revolution π
π§ Handler Destructuring Revolution
- β Modern TypeScript Patterns: All handlers now use object destructuring
- β
Clean Parameter Handling:
({ name, email, requestId }: HandlerParams) => {}
- β Type-Safe Function Signatures: Full TypeScript inference and validation
- β Repository Consistency: Matching destructuring patterns across all layers
π Intelligent Validation & Auto-Population
- β Smart Pattern Recognition: Email, URL, phone, UUID auto-detection
- β
Realistic Default Fields:
name
,description
,status
in every module - β
Module-Specific IDs:
todoId
,userId
,productId
instead of genericid
- β Enhanced Type System: Better optional field handling in UPDATE operations
ποΈ Framework & Architecture Improvements
- β Hono Compatibility: Full support for Hono framework with destructuring
- β Express Enhancement: Improved Express.js templates with modern patterns
- β Clean Architecture: Refined handler β repository pattern
- β Type-First Development: Types drive intelligent code generation
β¨ Developer Experience & Quality
- β Production-Ready Code: Realistic fields and professional patterns
- β Zero Configuration Issues: All generated code passes strict TypeScript
- β Smart Naming: Consistent professional naming across all generated files
- β Enhanced Testing: Tests automatically use exact type definitions
v3.1.6 - TypeScript & Build Fixes π§
π§ Critical Fixes:
- β
TypeScript Strict Mode: Fixed
'error' is of type 'unknown'
compilation errors - β Variable Naming: Fixed invalid JavaScript identifiers in generated repository code
- β Build Stability: All generated code now passes strict TypeScript compilation
- β Error Handling: Improved error handling patterns for better type safety
π¨ Code Quality Improvements:
- β
Import Type: All templates now use
import type
for type-only imports (TypeScript best practice) - β Dependency-Free: Removed shared errors dependency from generated repositories
- β Smart Variables: Variable names now use camelCase regardless of input format
v3.1.5 - Critical Bug Fix π
π§ Critical Fix:
- β
Module Import Error: Fixed
Cannot find module 'test-config-generator.service'
error - β Package Stability: Temporarily disabled test config generation to ensure package works
- β Global Installation: Package now works correctly when installed globally
v3.1.4 - Bug Fix Release π
π§ Critical Fix:
- β
Missing Module Fix: Fixed missing
test-config-generator.service
in published package - β Import Resolution: Resolved module import errors when using the npm package globally
v3.1.3 - Smart Naming System π¨
π Major Enhancement: Smart Naming Transformation
- β
Flexible Input: Accept any naming format (
kebab-case
,snake_case
,camelCase
,PascalCase
) - β Professional Output: Generate consistent, industry-standard naming conventions
- β Import Safety: Eliminate path mismatches and file not found errors
- β Framework Consistency: Works seamlessly with both Express and Hono
π§ Technical Improvements:
- β Template System: Updated all templates for consistent naming
- β Path Resolution: Fixed CLI path generation bugs
- β Code Quality: Professional naming throughout generated code
- β Error Prevention: No more invalid JavaScript identifiers
π Examples:
# All of these work perfectly now!
node-apis --name user-profile --crud # β user-profile/ directory
node-apis --name blog_post --crud # β blog-post/ directory
node-apis --name productCategory --crud # β product-category/ directory
π License
MIT License - see the LICENSE file for details.
π Why Developers Love This Tool
"Finally, a code generator that creates code I actually want to use in production!"
"The smart naming system is incredible - I can use any naming style and get perfect output!"
"The comprehensive test suite saved me days of writing tests manually."
"The performance monitoring and request tracing saved me hours of debugging."
"Clean architecture out of the box - no more service layer spaghetti!"
"The type-driven approach is genius - my handlers always match my data structure."
"Integration tests that actually test the real API - brilliant!"
"No more worrying about naming conventions - the generator handles it all professionally!"
"The generated code passes TypeScript strict mode without any errors - amazing!"
π What You Get
For CRUD APIs:
- ποΈ 22 files generated (5 operations Γ 4 files + routes + repository)
- π§ͺ 15 integration tests (3 per operation)
- β‘ Production-ready with monitoring and error handling
- π― Type-safe throughout the entire stack
For Custom APIs:
- ποΈ NΓ4 files generated (N operations Γ 4 files + routes + repository)
- π§ͺ NΓ3 integration tests (3 per operation)
- β‘ Production-ready with monitoring and error handling
- π― Type-safe throughout the entire stack
π Configuration File
The node-apis.config.json
file stores your preferences:
{
"version": "1.0.0",
"framework": "express",
"trpcStyle": false,
"database": {
"orm": "prisma",
"type": "postgresql"
},
"preferences": {
"autoFormat": true,
"generateTests": true,
"skipConfirmation": false
}
}
Configuration Options
framework
: Web framework (express
|hono
)trpcStyle
: Generate tRPC procedures instead of REST controllers (true
|false
)database
: Database settings (future feature)orm
: ORM preference (prisma
|typeorm
|drizzle
)type
: Database type (postgresql
|mysql
|sqlite
)
preferences
: Generation preferencesautoFormat
: Auto-format generated codegenerateTests
: Generate test filesskipConfirmation
: Skip confirmation prompts
Configuration Benefits
- π Faster Workflow - Skip repetitive framework selection prompts
- π₯ Team Consistency - Share config files across team members
- π§ Flexible Override - CLI options still work to override config
- π Future-Proof - Extensible for database ORM and other preferences
- πΎ Persistent - Settings saved locally per project
Ready to generate amazing APIs with comprehensive tests? π
npm install -g node-apis
node-apis --name book --crud
npm test # Run your generated tests!
π¨βπ» About the Author
Hi! I'm Sobebar Ali, a passionate Backend Developer and Founding AI Engineer at Capri AI. I built this tool to solve the repetitive task of creating production-ready API modules with proper architecture, comprehensive testing, and modern TypeScript patterns.
π― Why I Built This Tool
After years of building APIs professionally, I noticed developers spending too much time on boilerplate code instead of business logic. This generator bridges that gap by providing:
- Production-ready code that follows industry best practices
- Comprehensive testing that actually tests your APIs
- Type-safe patterns that prevent runtime errors
- Clean architecture that scales with your project
π Connect with Me
- π LinkedIn: linkedin.com/in/sobebarali
- π» GitHub: github.com/sobebarali
- π Website: sobebar.online
- π§ Email: sobebar.ali17@gmail.com
π Support This Project
If this tool saves you development time and helps your team build better APIs:
- β Star this repository on GitHub
- π¦ Share it with your development team
- π Report issues or suggest features
- π Follow me for more developer tools and insights
π€ Contributing
I welcome contributions! Whether it's:
- π Bug fixes
- β¨ New features (like tRPC support!)
- π Documentation improvements
- π§ͺ Test enhancements
Check out the contribution guidelines to get started.
Happy coding and testing! β¨
"Building this tool has been a journey of solving real developer problems. I hope it saves you as much time as it has saved me and my team!" - Sobebar Ali