-
Notifications
You must be signed in to change notification settings - Fork 539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: support runtime proxy using route rules #926
Conversation
Codecov Report
@@ Coverage Diff @@
## main #926 +/- ##
==========================================
+ Coverage 67.40% 67.73% +0.32%
==========================================
Files 59 59
Lines 5968 5979 +11
Branches 668 678 +10
==========================================
+ Hits 4023 4050 +27
+ Misses 1936 1920 -16
Partials 9 9
Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here. |
@yancyhuang It is partially with |
Will path rewrite support come? Like devProxy.
or i'm missing something about this topic? |
@antlionguard Something like this has same effect in route rules: |
Hi! π Is there an issue that tracks this? |
@pi0 , Thanks for this. Would it be possible to acheive something like this using variables? export default defineNuxtConfig({
routeRules: {
'/api': { proxy: NUXT_API_PROXY },
}
}) |
@blowsie For dynamic target, you should make a custom route handler and use |
@pi0, any way I can use the same for static build? (by |
@imzedi With a static build, you platform or reverse proxy has to handle that as no "nuxt/nitro" server is running |
BTW depends on the static deployment platform. One of proxy via route rule advantages is that we can technically generate platform (or reverse proxy) config. |
@pi0 e.g. for netlify you mean? |
Yes like this we can use for static presets. |
Hello, thanks for maintaining such an awesome library!
Thanks! |
This doesn't seem to work for websockets. The HTTP upgrade message is directly responded instead of forwarded to the proxy address. |
@keryigit Can you please open new feature request so i donβt forget this? π |
I've found a workaround with the tutorial by @manniL , its proxying normal requests and websockets (on the 2nd try) as well: // /server/api/[...].ts
import { joinURL } from 'ufo'
import { createProxyMiddleware } from 'http-proxy-middleware';
import { defineEventHandler } from 'h3';
// Get the runtimeconfig proxy url
const runtimeConfig = useRuntimeConfig()
const proxyUrl = (runtimeConfig.proxyToUrl as string) || "http://localhost"
const proxyUrlWs = (runtimeConfig.proxyToUrlWs as string) || "ws://localhost:80"
const wsSecure = proxyUrlWs.startsWith('wss')
const wsProxy = createProxyMiddleware({
target: proxyUrlWs, // Make sure this is correct
ws: true,
pathFilter: '/api/**',
pathRewrite: { '^/api': '' },
secure: wsSecure,
// changeOrigin: true,
on: {
proxyReqWs: (proxyReq, req, socket, options, head) => {
const wsPath = req.url;
// Construct the full WebSocket URL
const fullWsUrl = proxyUrlWs + wsPath;
console.info(`${CurrentTimeStamp()}\t[${wsSecure ? 'WSS' : 'WS'}]`, fullWsUrl);
}
}
});
/**
* PROXYING /api
* https://github.com/manniL/alexander-lichter-proxy-nuxt/blob/main/server/api/%5B...%5D.ts
* by manniL
*
* /api/** -> target/**
*
* proxies http and ws
* for ws nitro.experimental.websocket must be false in nuxt.config.ts
* @param event
*/
export default defineEventHandler(async (event) => {
var {
node,
path: _path,
_method
} = event;
// Check if it's a websocket request
// when a websocket request is detected, only the first event triggers this function dont know why
// everything works correctly tho, except very first connection is not proxied
if (node.req.headers.upgrade && node.req.headers.upgrade.toLowerCase() === 'websocket') {
wsProxy(node.req, node.res);
return;
}
// check the path
const path = _path.replace(/^\/api\//, '') // /api/users -> users
const target = joinURL(proxyUrl, path)
console.info(`${CurrentTimeStamp()}\t[${_method}]`, target);
// proxy it!
return proxyRequest(event, target)
})
function CurrentTimeStamp(): string {
const date = new Date();
const formattedDate = date.toLocaleString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
return formattedDate;
} |
Made trackers for WS Proxy support: |
@JoniLieh thanks for the response, but i don't recommend this solution, it will likely break with future versions of Nitro nor works with other runtimes.. |
@pi0 Thanks for the info, its for nuxt as well.
|
π Linked issue
#113
β Type of change
π Description
Support runtime proxy using route rules and
h3.proxyRequest
(universally works with fetch)Local support is pending unjs/h3#321
For more advance usages, users can always create a route like
routes/proxy/[...path].ts
and directly usereturn proxyRequest(path, { target })
and have full control over path handling, etc.π Checklist