Part of the alepha package. Import from alepha/server/proxy.
npm install alepha
Plugin for Alepha that provides a proxy server functionality.
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.
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
Basic proxy setup:
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:
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:
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:
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}