This is perfect if you want to migrate from Express.JS (or any other framework) to Hono without Downtime:
Just include this Proxy Server Endpoint at the End of your Hono Endpoints (usually index.ts):
// PROXY SERVER ENDPOINT
app.all('/*', async (c) => {
const legacyBackend = 'http://localhost:3000'; // proxy target
const newBackend = 'http://localhost:8787'; // proxy server location
try {
// Forward request body for POST/PUT/PATCH requests
const body = c.req.method !== 'GET' && c.req.method !== 'HEAD'
? await c.req.text()
: undefined;
const response = await axios.request({
url: c.req.url.replace(legacyBackend, newBackend),
method: c.req.method,
headers: c.req.header(),
data: body,
responseType: 'arraybuffer',
validateStatus: () => true // Don't throw on HTTP error status codes
});
const resBody = response.data;
return new Response(resBody, {
status: response.status,
statusText: response.statusText,
headers: response.headers as HeadersInit // seems mostly compatible
});
} catch (error) {
// Fallback error handling
return c.json({ error: 'Proxy error' }, 500);
}
});
Tags: ['How to migrate from Express to Hono', 'Hono Proxy Server', 'Hono proxy middleware']