alepha@docs:~/docs/packages/alepha/server$
cat proxy.md
1 min read
Last commit:

#Alepha - Server Proxy

#Installation

Part of the alepha package. Import from alepha/server/proxy.

npm install alepha

#Overview

Plugin for Alepha that provides a proxy server functionality.

#API Reference

#Primitives

Primitives are functions that define and configure various aspects of your application. They follow the convention of starting with $ and return configured primitive instances.

For more details, see the Primitives documentation.

#$proxy()

Creates a proxy primitive to forward requests to another server.

This primitive enables you to create reverse proxy functionality, allowing your Alepha server to forward requests to other services while maintaining a unified API surface. It's particularly useful for microservice architectures, API gateways, or when you need to aggregate multiple services behind a single endpoint.

Key Features

  • Path-based routing: Match specific paths or patterns to proxy
  • Dynamic targets: Support both static and dynamic target resolution
  • Request/Response hooks: Modify requests before forwarding and responses after receiving
  • URL rewriting: Transform URLs before forwarding to the target
  • Conditional proxying: Enable/disable proxies based on environment or conditions

Basic proxy setup:

ts
1import { $proxy } from "alepha/server/proxy";2 3class ApiGateway {4  // Forward all /api/* requests to external service5  api = $proxy({6    path: "/api/*",7    target: "https://api.example.com"8  });9}

Dynamic target with environment-based routing:

ts
1class ApiGateway {2  // Route to different environments based on configuration3  api = $proxy({4    path: "/api/*",5    target: () => process.env.NODE_ENV === "production"6      ? "https://api.prod.example.com"7      : "https://api.dev.example.com"8  });9}

Advanced proxy with request/response modification:

ts
 1class SecureProxy { 2  secure = $proxy({ 3    path: "/secure/*", 4    target: "https://secure-api.example.com", 5    beforeRequest: async (request, proxyRequest) => { 6      // Add authentication headers 7      proxyRequest.headers = { 8        ...proxyRequest.headers, 9        'Authorization': `Bearer ${await getServiceToken()}`,10        'X-Forwarded-For': request.headers['x-forwarded-for'] || request.ip11      };12    },13    afterResponse: async (request, proxyResponse) => {14      // Log response for monitoring15      console.log(`Proxied ${request.url} -> ${proxyResponse.status}`);16    },17    rewrite: (url) => {18      // Remove /secure prefix when forwarding19      url.pathname = url.pathname.replace('/secure', '');20    }21  });22}

Conditional proxy based on feature flags:

ts
1class FeatureProxy {2  newApi = $proxy({3    path: "/v2/*",4    target: "https://new-api.example.com",5    disabled: !process.env.ENABLE_V2_API // Disable if feature flag is off6  });7}
On This Page
No headings found...
ready
mainTypeScript
UTF-8packages_alepha_server_proxy.md