Express.js for Cloudflare Workers

Edge Computing, Simplified.

Build high-performance edge applications with a familiar Express-like API. Designed specifically for the Cloudflare Workers ecosystem.

2.3KB Runtime
Type-Safe
Zero Cold Start
index.js
import { createApp } from 'cloudworker';

export default {
  async fetch(request, env, ctx) {
    const app = createApp();
    
    // Apply global middleware
    app.use(async (req, res, next) => {
      const start = Date.now();
      await next();
      console.log(`${req.method} ${req.url} - ${Date.now() - start}ms`);
    });
    
    // Define routes
    app.get('/', async (req, res) => {
      return res.json({ message: 'Hello from CloudWorker!' });
    });
    
    app.get('/users/:id', async (req, res) => {
      const { id } = req.params;
      const user = await env.USERS.get(id);
      
      if (!user) {
        return res.status(404).json({ error: 'User not found' });
      }
      
      return res.json(JSON.parse(user));
    });
    
    app.post('/users', async (req, res) => {
      const id = crypto.randomUUID();
      await env.USERS.put(id, JSON.stringify({
        id,
        ...req.body,
        createdAt: new Date().toISOString()
      }));
      
      return res.status(201).json({ id });
    });
    
    return app.fetch(request, env, ctx);
  }
};
Features

Everything You Need For The Edge

CloudWorker combines the simplicity of Express.js with the power of Cloudflare Workers.

Express-like Routing

Familiar routing system with support for path parameters, wildcards, and route grouping.

Unified ORM

Work with KV, Durable Objects, and D1 databases using a single, consistent API.

Middleware System

Powerful middleware support for auth, logging, validation, and more.

Security Built-in

CSRF protection, rate limiting, safe headers, and other security features out of the box.

Template Engines

Built-in support for EJS, Handlebars, Mustache, and Pug template engines.

Real-time Support

WebSocket and Server-Sent Events support for building real-time applications.

Examples

See CloudWorker In Action

From simple APIs to complex applications, CloudWorker makes it easy.

api.js
import { createApp, Utils } from 'cloudworker';

export default {
  async fetch(request, env, ctx) {
    const app = createApp();
    
    // Apply middleware
    app.use(Utils.cors());
    app.use(Utils.logger());
    
    // Define API routes
    app.get('/api/products', async (req, res) => {
      // Get products from KV
      const { keys } = await env.PRODUCTS_KV.list();
      const products = await Promise.all(
        keys.map(async (key) => {
          const value = await env.PRODUCTS_KV.get(key.name);
          return JSON.parse(value);
        })
      );
      
      return res.json(products);
    });
    
    app.get('/api/products/:id', async (req, res) => {
      const { id } = req.params;
      const product = await env.PRODUCTS_KV.get(`product:${id}`);
      
      if (!product) {
        return res.status(404).json({ error: 'Product not found' });
      }
      
      return res.json(JSON.parse(product));
    });
    
    app.post('/api/products',
      // JWT authentication middleware
      Utils.jwt(env.JWT_SECRET),
      // Validate product data
      Utils.validate({
        body: {
          name: { type: 'string', required: true },
          price: { type: 'number', required: true, min: 0 },
          description: { type: 'string' }
        }
      }),
      async (req, res) => {
        const id = crypto.randomUUID();
        const product = {
          id,
          ...req.body,
          createdAt: new Date().toISOString(),
          createdBy: req.user.id
        };
        
        await env.PRODUCTS_KV.put(`product:${id}`, JSON.stringify(product));
        
        return res.status(201).json(product);
      }
    );
    
    app.delete('/api/products/:id',
      Utils.jwt(env.JWT_SECRET),
      Utils.authorize(['admin']),
      async (req, res) => {
        const { id } = req.params;
        await env.PRODUCTS_KV.delete(`product:${id}`);
        return res.status(204).send();
      }
    );
    
    return app.fetch(request, env, ctx);
  }
};
Get Started

Ready to Build on the Edge?

Start building your edge applications in minutes.

Quick Installation

1. Create a new Cloudflare Workers project
npm create cloudflare@latest my-app
2. Install CloudWorker
npm install cloudworker
3. Create your worker
import { createApp } from 'cloudworker';

export default {
  async fetch(request, env, ctx) {
    const app = createApp();
    
    app.get('/', async (req, res) => {
      return res.json({ message: 'Hello from CloudWorker!' });
    });
    
    return app.fetch(request, env, ctx);
  }
};
4. Deploy to Cloudflare
npx wrangler publish