Skip to content

Commit

Permalink
feat: allow using vite as a proxy for another vite server
Browse files Browse the repository at this point in the history
  • Loading branch information
divdavem committed May 16, 2023
1 parent 0fd4616 commit a32c182
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
8 changes: 3 additions & 5 deletions packages/vite/src/node/server/middlewares/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import httpProxy from 'http-proxy'
import type { Connect } from 'dep-types/connect'
import type { HttpProxy } from 'dep-types/http-proxy'
import colors from 'picocolors'
import { HMR_HEADER } from '../ws'
import { createDebugger } from '../../utils'
import type { CommonServerOptions, ResolvedConfig } from '../..'

Expand Down Expand Up @@ -103,10 +102,9 @@ export function proxyMiddleware(
if (doesProxyContextMatchUrl(context, url)) {
const [proxy, opts] = proxies[context]
if (
(opts.ws ||
opts.target?.toString().startsWith('ws:') ||
opts.target?.toString().startsWith('wss:')) &&
req.headers['sec-websocket-protocol'] !== HMR_HEADER
opts.ws ||
opts.target?.toString().startsWith('ws:') ||
opts.target?.toString().startsWith('wss:')
) {
if (opts.rewrite) {
req.url = opts.rewrite(url)
Expand Down
11 changes: 10 additions & 1 deletion packages/vite/src/node/server/ws.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import path from 'node:path'
import type { Server } from 'node:http'
import { STATUS_CODES, createServer as createHttpServer } from 'node:http'
import type { ServerOptions as HttpsServerOptions } from 'node:https'
Expand Down Expand Up @@ -101,9 +102,17 @@ export function createWebSocketServer(
const host = (hmr && hmr.host) || undefined

if (wsServer) {
let hmrBase = config.base
const hmrPath = hmr ? hmr.path : undefined
if (hmrPath) {
hmrBase = path.posix.join(hmrBase, hmrPath)
}
wss = new WebSocketServerRaw({ noServer: true })
wsServer.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] === HMR_HEADER) {
if (
req.headers['sec-websocket-protocol'] === HMR_HEADER &&
req.url === hmrBase
) {
wss.handleUpgrade(req, socket as Socket, head, (ws) => {
wss.emit('connection', ws, req)
})
Expand Down

0 comments on commit a32c182

Please sign in to comment.