Skip to content

Instantly share code, notes, and snippets.

@xfournet
Last active April 4, 2025 19:40
Show Gist options
  • Save xfournet/068592b3d1ddd488427b874b23f707bf to your computer and use it in GitHub Desktop.
Save xfournet/068592b3d1ddd488427b874b23f707bf to your computer and use it in GitHub Desktop.
Vite support for HTTP2 and proxy
import proxy from 'http2-proxy';
import type { Plugin, ProxyOptions } from 'vite';
export const pluginHttp2Proxy = (): Plugin => {
let routes: Record<string, string | ProxyOptions>;
return {
name: 'vite-plugin-http2-proxy',
config: (config) => {
const { server } = config;
routes = server?.proxy ?? {};
if (server) {
server.proxy = undefined;
}
return config;
},
configureServer: ({ config: { logger }, middlewares }) => {
Object.entries(routes).forEach(([route, target]) => {
if (typeof target !== 'string') {
throw new Error('ProxyOptions target are not supported yet, only string target are currently supported');
}
const { protocol, hostname, port } = new URL(target);
const options = {
protocol: protocol as 'http' | 'https',
hostname,
port: Number(port),
proxyTimeout: 60000,
};
middlewares.use(route, (req, res) => {
proxy.web(req, res, { ...options, path: req.originalUrl }, (err) => {
if (err) {
logger.error(`[http2-proxy] Error when proxying request on '${req.originalUrl}'`, { timestamp: true, error: err });
}
});
});
});
},
};
};
@nik-prostok
Copy link

nik-prostok commented May 8, 2024

@c1aphas I didn’t quite understand what configure should look like...

[vite] Internal server error: proxy.on is not a function

@c1aphas
Copy link

c1aphas commented May 8, 2024

@nik-prostok

configure(proxy) {
  // before
  // proxy.on('proxyRes', (proxyRes) => {...} 

  // now
  proxy.onRes = async (req, res, proxyRes) => {...}
}

@mjgerace
Copy link

mjgerace commented Apr 4, 2025

Here is my version with rewrite and configure support. Note that you should update your proxy config in configure() sections

proxy.on('proxyRes', (proxyRes) => {...} => proxy.onRes = async (req, res, proxyRes) => {...}

import type { Http2ServerRequest } from 'http2';
import type { Plugin, ProxyOptions } from 'vite';
import http2Proxy, { type http2WebOptions as Http2WebOptions } from 'http2-proxy';
....

This doesn't seem to work well with graphql subscriptions (stream types). Any insight as to why?

@sebinsua
Copy link

sebinsua commented Apr 4, 2025

^ Are there any error messages or strange behaviours that you've noticed?

@mjgerace
Copy link

mjgerace commented Apr 4, 2025

^ Are there any error messages or strange behaviours that you've noticed?

Hi Seb,

It says "proxy timeout". I tried to increase the timeout limit with no success. We are using server-side events, so its an http stream call that is open for a long time. It only does this on our http streams.

Appreciate the help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment