Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Rewrite Origin header if changeOrigin is true
Rewrites the header for both ws and http requests
  • Loading branch information
johnhunterarenko committed May 14, 2024
commit b9ebeeaf77d55130783f503df3795b676657cb85
40 changes: 28 additions & 12 deletions packages/vite/src/node/server/middlewares/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,29 @@ export interface ProxyOptions extends HttpProxy.ServerOptions {
) => void | null | undefined | false | string
}

const setOriginHeader = (
proxyReq: http.ClientRequest,
options: HttpProxy.ServerOptions,
) => {
// Browsers may send Origin headers even with same-origin
// requests. It is common for WebSocket servers to check the Origin
// header, so if changeOrigin is true we change the Origin to match
// the target URL.
// https://github.com/http-party/node-http-proxy/issues/1669
if (options.changeOrigin) {
const { target } = options

if (proxyReq.getHeader('origin') && target) {
const changedOrigin =
typeof target === 'object'
? `${target.protocol}//${target.host}`
: target

proxyReq.setHeader('origin', changedOrigin)
}
}
}

export function proxyMiddleware(
httpServer: HttpServer | null,
options: NonNullable<CommonServerOptions['proxy']>,
Expand Down Expand Up @@ -89,19 +112,12 @@ export function proxyMiddleware(
}
})

proxy.on('proxyReq', (proxyReq, req, res, options) => {
setOriginHeader(proxyReq, options)
})

proxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => {
// Browsers may send Origin headers even with same-origin
// requests. It is common for WebSocket servers to check the Origin
// header, so we have to change the Origin to match
// the target URL.
if (proxyReq.getHeader('origin') && options.target) {
const target =
typeof options.target === 'object'
? `${options.target.protocol}//${options.target.host}`
: options.target

proxyReq.setHeader('origin', target)
}
setOriginHeader(proxyReq, options)

socket.on('error', (err) => {
config.logger.error(
Expand Down