Socket
Book a DemoInstallSign in
Socket

create-bini-app

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

create-bini-app

Bini.js: Ultra-high-performance enterprise-grade React framework with automatic source code protection, Next.js-like file-based routing, head-only SSR, production-ready API routes, Fastify server, TypeScript support, and built-in security middleware. The

Source
npmnpm
Version
9.1.5
Version published
Weekly downloads
136
-25.68%
Maintainers
1
Weekly downloads
 
Created
Source

Bini.js CLI v9.1.5 – Complete Production-Ready Documentation

██████╗ ██╗███╗   ██╗██╗      ██╗███████╗
██╔══██╗██║████╗  ██║██║      ██║██╔════╝
██████╔╝██║██╔██╗ ██║██║      ██║███████║
██╔══██╗██║██║╚██╗██║██║ ██╗  ██║╚════██║
██████╔╝██║██║ ╚████║██║ ╚█████╔╝███████║
╚═════╝ ╚═╝╚═╝  ╚═══╝╚═╝  ╚════╝ ╚══════╝

Build lightning-fast, source-protected React apps — powered by Vite & Fastify

npm version total downloads license node version

vite react fastify typescript

🚀 What's New: TypeScript API Routes & Enhanced File Structure (v9.1.5)

🔌 API Routes Now Support TypeScript

API routes now fully support TypeScript (.ts) files alongside JavaScript, with all routes moved to src/app/api/ for a unified Next.js-compatible structure:

// src/app/api/users.ts
import type { Request, Response } from 'fastify';

interface User {
  id: number;
  name: string;
  email: string;
  createdAt: string;
}

interface CreateUserBody {
  name: string;
  email: string;
}

interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
  timestamp: string;
}

export default function handler(
  req: Request,
  res: Response
): ApiResponse<User | User[] | null> {
  const timestamp = new Date().toISOString();
  
  switch (req.method) {
    case 'GET':
      return {
        success: true,
        data: [
          { id: 1, name: 'Alice', email: 'alice@example.com', createdAt: timestamp }
        ],
        timestamp
      };
    
    case 'POST':
      const { name, email } = req.body as CreateUserBody;
      
      if (!name || !email) {
        res.status(400);
        return {
          success: false,
          error: 'Name and email required',
          timestamp
        };
      }
      
      res.status(201);
      return {
        success: true,
        data: { id: Date.now(), name, email, createdAt: timestamp },
        timestamp
      };
    
    default:
      res.status(405);
      return { success: false, error: 'Method not allowed', timestamp };
  }
}

📁 New Unified File Structure

API routes now live inside src/app/api/ alongside your pages:

src/app/
├── layout.tsx                    # Root layout
├── page.tsx                      # Home page (/)
├── about/page.tsx                # /about
├── blog/[slug]/page.tsx          # /blog/:slug
├── api/                          # API ROUTES (NEW LOCATION)
│   ├── hello.ts                  # TypeScript API route
│   ├── users.ts                  # TypeScript API route
│   ├── products/[id].ts          # Dynamic TypeScript API route
│   └── search/query.js           # JavaScript API route
└── globals.css                   # Global styles

Key Improvements

  • TypeScript Compilation – API routes automatically compiled to JavaScript
  • Hot Reload – API changes reflect instantly during development
  • Type Safety – Full IntelliSense and type checking
  • Mixed Language Support – Use both .ts and .js in same project
  • Dynamic Routes – Support for [id] and [...slug] patterns
  • Next.js Compatible – Familiar structure for Next.js developers

Overview

Build source-code-protected React apps with Next.js-style file-based routing and built-in API routes (with full TypeScript support), powered by Vite and Fastify. Your source code stays hidden while your site remains fully functional and SEO-optimized.

Key Differentiators:

  • 🔒 Source Code Protection – Compiled & minified production builds
  • Fastify Production Server – 2x faster than Express, HTTP/2 support
  • 🛡️ Rate Limiting – Built-in protection (100 req/15min per IP)
  • 🔌 API Routes Everywhere – Work in dev, preview, AND production with full TypeScript support
  • 🎯 File-Based Routing – Like Next.js, powered by Vite
  • 📱 PWA Ready – Auto-generated favicons, manifests, social meta
  • 🔐 Security Hardened – Helmet headers, CORS, sanitization, path validation
  • 📊 Monitoring Ready – Health checks & metrics endpoints

Getting Started

npx create-bini-app@latest my-app
cd my-app
npm install
npm run dev

Your browser opens automatically at http://localhost:3000.

Installation

Interactive Setup

npx create-bini-app@latest

Select your preferences:

  • TypeScript or JavaScript
  • Styling: Tailwind CSS, CSS Modules, or vanilla CSS
  • Additional options via command-line flags

Command-Line Setup

# Full-featured with TypeScript and Tailwind
npx create-bini-app@latest my-app --typescript --tailwind

# With CSS Modules
npx create-bini-app@latest my-app --css-modules

# JavaScript only
npx create-bini-app@latest my-app --javascript

# Override existing directory
npx create-bini-app@latest my-app --force

# Skip automatic dependency installation
npx create-bini-app@latest my-app --skip-install

# Show detailed logs
npx create-bini-app@latest my-app --verbose

Supported Package Managers

Bini.js automatically detects and uses your preferred package manager in priority order:

  • bun – Fastest bundler
  • pnpm – Space-efficient
  • yarn – Feature-rich
  • npm – Most compatible

Project Architecture

my-app/
├── src/
│   ├── app/                         # File-based routing (Next.js-like)
│   │   ├── layout.tsx               # Root layout (metadata, SEO)
│   │   ├── page.tsx                 # Home page (/)
│   │   ├── about/page.tsx           # Static route (/about)
│   │   ├── blog/[slug]/page.tsx     # Dynamic route (/blog/:slug)
│   │   ├── api/                     # API routes (TypeScript & JavaScript)
│   │   │   ├── hello.ts             # TypeScript API route example
│   │   │   ├── users.ts             # TypeScript API route
│   │   │   ├── search/query.js      # JavaScript API route
│   │   │   └── products/[id].ts     # Dynamic TypeScript API route
│   │   └── globals.css              # Global stylesheet + CSS variables
│   ├── App.tsx                      # Root component (auto-generated)
│   └── main.tsx                     # Application entry point
├── public/                          # Static assets & auto-generated favicons
│   ├── favicon.svg                  # Rebranded ß icon (SVG)
│   ├── favicon.png                  # Main favicon (512×512)
│   ├── favicon-16x16.png            # 16px resolution
│   ├── favicon-32x32.png            # 32px resolution
│   ├── favicon-64x64.png            # 64px resolution
│   ├── favicon-180x180.png          # 180px for iOS
│   ├── favicon-512x512.png          # 512px for Android
│   ├── apple-touch-icon.png         # iOS home screen icon
│   ├── og-image.png                 # Social media preview (1200×630)
│   └── site.webmanifest             # PWA manifest
├── bini/
│   ├── internal/plugins/            # Framework runtime (DO NOT EDIT)
│   │   ├── router.js                # File-based routing + race condition fix
│   │   ├── api.js                   # API middleware + TypeScript support
│   │   ├── ssr.js                   # SSR meta tag injection
│   │   ├── badge.js                 # Dev console badge
│   │   ├── preview.js               # Preview server config
│   │   └── env-checker.js           # Environment file detection
│   └── bini.d.ts                    # TypeScript definitions
├── .bini/
│   ├── dist/                        # Production build (read-only)
│   └── cache/                       # Build cache
├── index.html                       # HTML template
├── vite.config.mjs                  # Vite config (imports bini.config.mjs)
├── bini.config.mjs                  # Bini.js configuration
├── api-server.js                    # ⚡ Fastify production server
├── package.json                     # Dependencies
├── tsconfig.json                    # TypeScript (if enabled)
├── tailwind.config.js               # Tailwind CSS (if enabled)
├── .env.example                     # Environment variables template
└── README.md                        # Project documentation

File-Based Routing

Pages are automatically discovered and routed based on file location:

src/app/
├── page.tsx              → /
├── about/page.tsx        → /about
├── blog/page.tsx         → /blog
├── blog/[slug]/page.tsx  → /blog/:slug
└── admin/[...id]/page.tsx → /admin/* (catch-all)

Creating Routes

Static Route:

// src/app/about/page.tsx
export default function AboutPage() {
  return (
    <div>
      <h1>About Us</h1>
      <p>Company information here.</p>
    </div>
  );
}

Dynamic Route:

// src/app/blog/[slug]/page.tsx
import { useParams } from 'react-router-dom';

export default function BlogPost() {
  const { slug } = useParams();
  
  return (
    <article>
      <h1>Post: {slug}</h1>
      <p>Dynamic content for {slug}</p>
    </article>
  );
}

Routes are automatically generated at startup and hot-reload during development. Race conditions are prevented by the async lock system.

API Routes

Location: src/app/api/

API routes now live inside the src/app/ directory alongside your pages for a cohesive, Next.js-compatible structure.

TypeScript API Routes

Create type-safe API routes with full TypeScript support:

// src/app/api/products/[id].ts
import type { Request, Response } from 'fastify';

interface Product {
  id: string;
  name: string;
  price: number;
  stock: number;
}

export default function handler(
  req: Request,
  res: Response
): { success: boolean; data?: Product; error?: string } {
  const { id } = req.query;
  
  if (req.method === 'GET') {
    return {
      success: true,
      data: {
        id: id as string,
        name: `Product ${id}`,
        price: 99.99,
        stock: 50
      }
    };
  }
  
  res.status(405);
  return { success: false, error: 'Method not allowed' };
}

JavaScript API Routes

// src/app/api/hello.js
export default function handler(req, res) {
  return {
    message: 'Hello from Bini.js API!',
    timestamp: new Date().toISOString(),
    method: req.method
  };
}

Request Methods

// src/app/api/users.ts
export default function handler(req: Request, res: Response) {
  switch (req.method) {
    case 'GET':
      // Fetch all users
      return { users: [] };
    
    case 'POST':
      // Create new user
      const { name, email } = req.body;
      return { id: Date.now(), name, email, created: true };
    
    case 'PUT':
      // Update user
      return { updated: true };
    
    case 'DELETE':
      // Delete user
      return { deleted: true };
    
    default:
      res.status(405);
      return { error: 'Method not allowed' };
  }
}

Query Parameters & Sanitization

// src/app/api/search.ts
export default function handler(req: Request, res: Response) {
  const { q, limit = '10', offset = '0' } = req.query;
  
  // Input sanitized automatically
  return {
    query: q,
    limit: parseInt(limit as string),
    offset: parseInt(offset as string),
    results: [],
    timestamp: new Date().toISOString()
  };
}

Request/Response API

export default function handler(req: Request, res: Response) {
  // Request Properties
  req.method          // 'GET', 'POST', 'PUT', 'DELETE', 'PATCH'
  req.url             // Full request URL
  req.headers         // HTTP headers object
  req.body            // Parsed & sanitized JSON (POST/PUT/PATCH/DELETE)
  req.query           // Query parameters object (sanitized)
  req.ip              // Client IP address
  
  // Response Methods
  res.status(code)             // Set HTTP status code
  res.setHeader(name, value)   // Set response header
  res.json(data)               // Send JSON response
  res.send(data)               // Send response (auto-detects format)
  res.end(data)                // End response with optional data
  
  return data;  // Auto-serialized to JSON (preferred)
}

API Route Specifications

FeatureDetails
Request Timeout30 seconds per request
Body Size Limit1MB default (configurable)
Rate Limiting100 requests per 15 minutes per IP
Response FormatAutomatically JSON-serialized
SecurityPath traversal prevention, prototype pollution checks, input sanitization
Caching5-minute TTL for handlers (prevents memory leaks)
AvailabilityWorks in development, preview, AND production
Performance2x faster with Fastify vs Express
Language SupportBoth TypeScript (.ts) and JavaScript (.js)
Hot ReloadAutomatic reload in development when API files change
TypeScript CompilationAutomatic transpilation to JavaScript

Rate Limiting Headers

All API responses include rate limit information:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1730396400

SEO & Metadata

Define all SEO information in your root layout:

// src/app/layout.tsx

export const metadata = {
  title: 'My Application',
  description: 'High-performance React application',
  keywords: ['react', 'bini', 'fastify', 'vite'],
  
  openGraph: {
    title: 'My Application',
    description: 'Experience fast, modern development',
    url: 'https://myapp.com',
    images: [{ 
      url: '/og-image.png', 
      width: 1200, 
      height: 630,
      alt: 'My Application Preview'
    }]
  },
  
  twitter: {
    card: 'summary_large_image',
    title: 'My Application',
    description: 'Fast React development',
    creator: '@yourhandle',
    images: ['/og-image.png']
  },
  
  icons: {
    icon: [
      { url: '/favicon.svg', type: 'image/svg+xml' },
      { url: '/favicon-16x16.png', type: 'image/png', sizes: '16x16' },
      { url: '/favicon-32x32.png', type: 'image/png', sizes: '32x32' }
    ],
    apple: [{ url: '/apple-touch-icon.png', sizes: '180x180' }]
  },
  
  manifest: '/site.webmanifest'
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>{/* Meta tags auto-injected */}</head>
      <body>{children}</body>
    </html>
  );
}

All metadata is automatically injected into the HTML head with proper OpenGraph, Twitter Card, and favicon tags.

Build & Deploy

Development

npm run dev

Features:

  • ⚡ Hot Module Replacement (HMR) with sub-50ms updates
  • 🔌 Automatic file-based routing with race condition protection
  • 🌐 Browser auto-opens at http://localhost:3000
  • 📋 Shows which .env files are loaded
  • 💾 Full source maps for debugging
  • 📊 Routes displayed in badge menu when clicked
  • 🖥️ Network IP detection and display
  • 🔄 TypeScript API routes with hot reload
  • 📝 Development console badge indicator

Preview Production Build

npm run preview

Preview the production build locally before deployment:

  • ✅ Runs optimized production bundle
  • 🔌 Full API routes working via Vite middleware
  • 📱 Gzip compression enabled
  • ⚡ Source maps disabled (production mode)
  • 📋 Shows loaded .env files like Next.js
  • 🌐 Displays local and network URLs
  • 🔄 TypeScript API routes compiled and working

Production Build

npm run build

Creates optimized production bundle in .bini/dist/:

  • ✅ Minified JavaScript (no source maps)
  • ✅ Code splitting and tree-shaking
  • ✅ CSS minification
  • ✅ Asset optimization
  • ✅ Source code protection enabled
  • ✅ Build validation (validates output directory)
  • ✅ TypeScript compilation for API routes
  • ✅ Ready for deployment to any static host

Production Server

npm run start
# or
npm start

Launches Fastify production server with:

  • ✅ Static file serving from .bini/dist/ (validated before start)
  • ✅ Full API routes working at /api/*
  • ✅ TypeScript API routes compiled and executed
  • ✅ Intelligent Port Management – Auto-detects blocked ports
  • ✅ Process Detection – Shows what's blocking ports
  • ✅ IPv4 & IPv6 Support – Handles both loopback addresses
  • ✅ Helmet security headers (CSP, HSTS, X-Frame-Options)
  • ✅ Rate limiting (100 req/15 min per IP with headers)
  • ✅ Graceful Shutdown – 30-second timeout for active requests
  • ✅ Health Check Endpoint – /health for monitoring
  • ✅ Metrics Endpoint – /metrics for Prometheus/monitoring
  • ✅ Gzip & Brotli compression (auto-enabled)
  • ✅ Auto-opens Browser – Works on Windows/macOS/Linux
  • ✅ Network IP Detection – Shows all accessible URLs
  • ✅ Shows environment files loaded on startup
  • ✅ HTTP/2 support for better performance

Configuration

bini.config.mjs

Configure your application settings:

export default {
  outDir: '.bini',           // Build output directory
  port: 3000,                // Development server port
  host: 'localhost',         // HMR host
  api: {
    dir: 'src/app/api',      // API routes directory
    bodySizeLimit: '1mb'     // Request body size limit
  },
  static: {
    dir: 'public',           // Static files directory
    maxAge: 3600             // Cache max-age in seconds
  },
  build: {
    minify: true,            // Minify output
    sourcemap: true          // Include source maps
  }
};

Environment Variables

Create a .env.local file for environment-specific settings:

VITE_APP_NAME=My Application
VITE_APP_URL=http://localhost:3000
VITE_API_BASE=/api

# Production
SKIP_UPDATE_CHECK=true
CORS_ENABLED=true
RATE_LIMIT=1000
NODE_ENV=production
PORT=3000
HMR_HOST=0.0.0.0

Performance & Security

Performance Features

  • Vite – Sub-second module replacement
  • Fastify – 2x faster than Express (1000+ req/s vs 500)
  • Tree Shaking – Unused code removed
  • Code Splitting – Vendor code separated
  • Gzip Compression – 70%+ reduction (automatic)
  • Caching – TTL-based handler caching (5 minutes)
  • Minification – All assets minified
  • HTTP/2 – Full HTTP/2 support in Fastify
  • TypeScript Optimization – Efficient transpilation with caching

Security Features

FeatureDetails
Path ValidationAll file paths validated, traversal attacks prevented
Input SanitizationDeep object traversal, circular reference detection
Prototype PollutionDangerous properties blocked (__proto__, constructor)
Rate Limiting100 req/15min per IP (configurable) with headers
Helmet HeadersCSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer Policy
CORS ProtectionOptional CORS with whitelist support
Graceful Shutdown30-second timeout for active requests (SIGTERM/SIGINT)
Race Condition ProtectionAsync locks prevent simultaneous operations
Memory Leak PreventionTTL-based cache with automatic cleanup
Process DetectionIdentifies blocking processes on Windows/macOS/Linux
Port ScanningIntelligent port selection with <1 second detection
TypeScript SafetyType-checked API routes prevent runtime errors

System Requirements

  • Node.js: 18.0.0 or higher
  • Disk Space: 150MB (node_modules + build)
  • RAM: 512MB minimum (1GB recommended)
  • OS: macOS, Linux, Windows (WSL2 recommended)

Troubleshooting

Port Already in Use

# Bini.js automatically handles this – just run the command
npm run dev

# Use different port if needed
PORT=3001 npm start

Build Directory Not Found

# Solution: Run build first
npm run build

# Then start production server
npm start

API Routes Not Working

# Check API route location: src/app/api/

# Verify file structure:
# ✅ src/app/api/hello.ts or hello.js
# ❌ src/api/hello.ts (wrong location)

# Default export required:
export default function handler(req, res) {
  return { message: 'Hello' };
}

Changelog

v9.1.5 (Current - TypeScript API Routes Release)

  • API Routes in src/app/api/ – Unified Next.js-compatible structure
  • Full TypeScript Support – API routes now support .ts files
  • Type Safety – IntelliSense and type checking for API handlers
  • Dynamic API Routes – Support for [id] and [...slug] patterns
  • Mixed Language Support – Use both .ts and .js in same project
  • Hot Reload – TypeScript API changes reflect instantly
  • Automatic Compilation – TypeScript compiled to JavaScript automatically
  • Enhanced DX – Better developer experience with type hints
  • HTML Minification Control – Configure HTML output formatting (pretty-print or minified)
  • Configurable Build Output – Choose between readable HTML (dev) or optimized (prod)

v9.1.4 (Circular Badge Animation Release)

  • Circular Loading Badge – New animated ß icon with stroke effect
  • Pulsing Circle Animation – Expands and contracts on page load
  • Stroke Drawing Effect – Gradient line draws with easing
  • Auto-Stop Animation – Stops when page fully loaded
  • Auto-Restart Logic – Restarts if page takes too long
  • Mobile Responsive – Badge shrinks on small screens
  • Smooth 60fps – Hardware-accelerated CSS animations
  • No Performance Impact – Badge adds only ~1.5MB memory overhead
  • Enhanced DX – Better visual feedback during page loads
  • Animation Customizable – Easy to adjust timings and colors

v9.1.3 (Fastify Production Server Release)

  • Fastify 4.28 – 2x faster than Express
  • Intelligent Port Management – Auto-detects and avoids blocked ports
  • Health & Metrics Endpoints/health and /metrics for monitoring
  • Graceful Shutdown – 30-second timeout with active request tracking
  • Security Headers – CSP, HSTS, X-Frame-Options

License

MIT – Free for personal and commercial use.

Bini.js v9.1.5 — Built with ❤️ using Vite, React, and Fastify

GitHub · Documentation · npm · Sponsor

Keywords

bini

FAQs

Package last updated on 08 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts