Proxy
The Proxy middleware allows you to forward requests to another server, acting as a reverse proxy. It supports both HTTP and WebSocket connections.
import { Proxy } from 'shokupan';
// Forward /api requests to an external APIapp.use('/api', Proxy({ target: 'https://api.external.com', changeOrigin: true}));Options
Section titled “Options”| Option | Type | Required | Description |
|---|---|---|---|
target | string | Yes | The target URL to forward requests to. |
pathRewrite | (path: string) => string | No | Function to rewrite the URL path before forwarding. |
changeOrigin | boolean | No | Changes the origin of the host header to the target URL. |
ws | boolean | No | Enable WebSocket proxying. |
headers | Record<string, string> | No | Custom headers to add to the forwarded request. |
Examples
Section titled “Examples”Path Rewriting
Section titled “Path Rewriting”Remove the prefix from the forwarded path:
app.use('/api/v1', Proxy({ target: 'https://api.service.com', pathRewrite: (path) => path.replace('/api/v1', '')}));// request: /api/v1/users -> target: https://api.service.com/usersWebSocket Proxy
Section titled “WebSocket Proxy”Forward WebSocket connections:
app.use('/socket', Proxy({ target: 'ws://ws.service.com', ws: true}));