Skip to content

Instantly share code, notes, and snippets.

@xfournet
Last active May 8, 2024 16:27
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 });
}
});
});
});
},
};
};
@c1aphas
Copy link

c1aphas commented May 8, 2024

@nik-prostok

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

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

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