Skip to content

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 API
app.use('/api', Proxy({
target: 'https://api.external.com',
changeOrigin: true
}));
OptionTypeRequiredDescription
targetstringYesThe target URL to forward requests to.
pathRewrite(path: string) => stringNoFunction to rewrite the URL path before forwarding.
changeOriginbooleanNoChanges the origin of the host header to the target URL.
wsbooleanNoEnable WebSocket proxying.
headersRecord<string, string>NoCustom headers to add to the forwarded request.

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/users

Forward WebSocket connections:

app.use('/socket', Proxy({
target: 'ws://ws.service.com',
ws: true
}));