Skip to content

perf: cache compiled RegExp for proxy context matching#22380

Open
tomohiro86 wants to merge 1 commit into
vitejs:mainfrom
tomohiro86:fix/proxy-regexp-cache
Open

perf: cache compiled RegExp for proxy context matching#22380
tomohiro86 wants to merge 1 commit into
vitejs:mainfrom
tomohiro86:fix/proxy-regexp-cache

Conversation

@tomohiro86
Copy link
Copy Markdown

@tomohiro86 tomohiro86 commented May 3, 2026

Summary

  • server.proxy contexts starting with ^ were compiled via new RegExp(context) on every incoming request
  • Pre-compile them once during proxyMiddleware initialization and reuse via a Map cache

Details

doesProxyContextMatchUrl was called on every request for every proxy context. When a context started with ^, it created a new RegExp object each time — regex compilation is relatively expensive and the pattern never changes after config is loaded.

// before: compiled on every request
(context[0] === '^' && new RegExp(context).test(url))

// after: compiled once at startup, reused from cache
regexCache.get(context)!.test(url)

The fix adds a regexCache: Map<string, RegExp> inside proxyMiddleware that is populated when the proxy entries are initialized, and passes it down to doesProxyContextMatchUrl.

Test plan

  • Existing proxy-related tests pass
  • Dev server with server.proxy: { '^/api': '...' } routes requests correctly

Regex patterns in `server.proxy` starting with `^` were compiled via
`new RegExp(context)` on every incoming request. Pre-compile them once
during `proxyMiddleware` initialization and reuse via a Map cache.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant