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 🙏

© 2025 – Pkg Stats / Ryan Hefner

blog-api-v2-example

v2.0.1

Published

Blog API using API Forge V2 configuration system

Downloads

6

Readme

Blog API V2 - Configuration Driven Example

This example demonstrates a complete blog API using API Forge V2's configuration-driven approach.

Features

  • 🔐 Authentication: JWT-based auth with sessions
  • 📝 Blog Posts: Full CRUD operations with pagination
  • 💬 Comments: Nested comments on posts
  • 👤 User Management: Profile updates and roles
  • 📁 File Upload: Image uploads with processing
  • 🚀 Real-time Updates: SSE for live notifications
  • 📚 API Documentation: Auto-generated Swagger docs
  • 🔧 TypeScript SDK: Auto-generated client library
  • 🛡️ Security: Rate limiting, input validation, CSRF protection
  • Caching: Redis-based response caching

Quick Start

1. Install Dependencies

cd examples/blog-api-v2
bun install

2. Setup Environment

Copy the example environment file:

cp .env.example .env

Edit .env with your configuration:

# Required
JWT_SECRET=your-secret-key-change-in-production

# Optional (defaults provided)
PORT=3001
REDIS_URL=redis://localhost:6379

3. Start the Server

bun run server.ts

The server will start at http://localhost:3001

4. Access Resources

  • API Documentation: http://localhost:3001/docs
  • Health Check: http://localhost:3001/health
  • API Info: http://localhost:3001/api

Project Structure

blog-api-v2/
├── .api-forge.json      # Main configuration file
├── .env.example         # Environment variables template
├── server.ts           # Minimal server code (< 100 lines!)
├── api-configs/        # API endpoint configurations
│   ├── auth.json      # Authentication endpoints
│   ├── posts.json     # Blog post endpoints
│   ├── comments.json  # Comment endpoints
│   ├── users.json     # User management
│   └── events.json    # SSE real-time events
├── handlers/           # Custom business logic
│   ├── auth.js       # Auth handlers
│   ├── posts.js      # Post handlers
│   ├── comments.js   # Comment handlers
│   ├── users.js      # User handlers
│   └── events.js     # SSE handlers
└── sdk/               # Auto-generated TypeScript SDK

Configuration Highlights

Plugin Configuration

All plugins are configured in .api-forge.json:

{
  "plugins": {
    "@api-forge/redis": {
      "enabled": "${REDIS_ENABLED:-true}",
      "config": {
        "url": "${REDIS_URL:-redis://localhost:6379}"
      }
    },
    "@api-forge/auth": {
      "enabled": true,
      "config": {
        "jwt": {
          "secret": "${JWT_SECRET}"
        }
      }
    }
  }
}

API Configuration

Each API endpoint is defined in a JSON file:

{
  "id": "posts",
  "route": {
    "path": "/api/posts/:id?",
    "methods": ["GET", "POST", "PUT", "DELETE"]
  },
  "auth": {
    "required": true,
    "roles": {
      "DELETE": ["admin"]
    }
  },
  "cache": {
    "enabled": true,
    "ttl": 300
  }
}

API Endpoints

Authentication

# Register
curl -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"password123","name":"John Doe"}'

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

Posts

# List posts
curl http://localhost:3001/api/posts

# Get single post
curl http://localhost:3001/api/posts/1

# Create post (requires auth)
curl -X POST http://localhost:3001/api/posts \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"My Post","content":"Hello World","status":"published"}'

Real-time Events (SSE)

// Connect to SSE endpoint
const eventSource = new EventSource(
  'http://localhost:3001/api/events', 
  { headers: { 'Authorization': 'Bearer YOUR_TOKEN' } }
);

eventSource.addEventListener('post:created', (event) => {
  const data = JSON.parse(event.data);
  console.log('New post created:', data);
});

TypeScript SDK

The SDK is auto-generated when the server starts:

import { BlogAPI } from './sdk';

const api = new BlogAPI({
  baseUrl: 'http://localhost:3001',
  token: 'YOUR_JWT_TOKEN'
});

// Type-safe API calls
const posts = await api.posts.list({ page: 1, limit: 10 });
const post = await api.posts.create({
  title: 'My Post',
  content: 'Hello World'
});

Environment Variables

| Variable | Description | Default | |----------|-------------|---------| | NODE_ENV | Environment (development/production) | development | | PORT | Server port | 3001 | | REDIS_ENABLED | Enable Redis caching | true | | REDIS_URL | Redis connection URL | redis://localhost:6379 | | JWT_SECRET | Secret for JWT signing | (required) | | CORS_ORIGIN | Allowed CORS origins | * | | STORAGE_TYPE | File storage type (local/s3) | local |

Key Differences from V1

  1. No Plugin Code: All plugins configured in JSON
  2. Environment Variables: Full support with defaults
  3. Minimal Server Code: < 100 lines vs 500+ in V1
  4. Centralized Config: Single .api-forge.json file
  5. Better Deployment: Environment-specific configs

Production Deployment

  1. Set production environment variables
  2. Use production configuration:
    NODE_ENV=production bun run server.ts
  3. Configure reverse proxy (nginx/caddy)
  4. Set up process manager (PM2/systemd)

Extending the API

Add New Endpoint

  1. Create configuration in api-configs/
  2. Add handlers in handlers/ if needed
  3. Restart server (or use hot reload in dev)

Add New Plugin

  1. Install the plugin package
  2. Add configuration to .api-forge.json
  3. Set any required environment variables

Troubleshooting

Redis Connection Failed

  • Ensure Redis is running: redis-cli ping
  • Check REDIS_URL environment variable

Authentication Errors

  • Verify JWT_SECRET is set
  • Check token expiration

SDK Generation Failed

  • Ensure write permissions for ./sdk directory
  • Check console for specific errors

Learn More