Skip to content
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

Standalone server does not proxy WebSocket connections #44209

Open
1 task done
georgeclaghorn opened this issue Dec 21, 2022 · 2 comments
Open
1 task done

Standalone server does not proxy WebSocket connections #44209

georgeclaghorn opened this issue Dec 21, 2022 · 2 comments
Labels
bug Issue was opened via the bug report template.

Comments

@georgeclaghorn
Copy link

georgeclaghorn commented Dec 21, 2022

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 22.1.0: Sun Oct  9 20:14:30 PDT 2022; root:xnu-8792.41.9~2/RELEASE_ARM64_T8103
Binaries:
  Node: 16.16.0
  npm: 8.11.0
  Yarn: 1.22.15
  pnpm: 6.11.0
Relevant packages:
  next: 13.0.8-canary.2
  eslint-config-next: 13.0.0
  react: 18.2.0
  react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

Standalone mode (output: "standalone")

Link to the code that reproduces this issue

https://github.com/georgeclaghorn/next-standalone-ws-rewrites

To Reproduce

  1. Clone the sample repo and cd into it.

  2. Install dependencies: npm install.

  3. Build and run the app: npm run build && npm run start.

  4. Open http://localhost:3000 in any browser. See that the WebSocket connection is successfully established.

  5. Build and run the standalone server:

    npm run build
    cp -R public .next/standalone
    cp -R .next/static .next/standalone/.next
    node .next/standalone/server.js
    
  6. Refresh http://localhost:3000 in your browser. See that the WebSocket connection is stuck in the connecting state.

Describe the Bug

#39463 added support for proxying WebSocket connections through rewrites, and it does work via next dev and next start. The standalone server does not proxy WebSocket connections, though. They get stuck in the connecting state.

Expected Behavior

The standalone server proxies WebSocket connections through rewrites, just like next start. WebSocket connections can be successfully established to servers behind rewrites.

Which browser are you using? (if relevant)

N/A

How are you deploying your application? (if relevant)

N/A

@georgeclaghorn georgeclaghorn added the bug Issue was opened via the bug report template. label Dec 21, 2022
@georgeclaghorn
Copy link
Author

This change to the generated .next/standalone/server.js fixes the issue for me:

--- /Users/george/Desktop/server-old.js	2022-12-20 20:10:24
+++ /Users/george/Desktop/server-new.js	2022-12-20 20:12:03
@@ -12,11 +12,12 @@
   process.on('SIGINT', () => process.exit(0))
 }
 
-let handler
+let requestHandler
+let upgradeHandler
 
 const server = http.createServer(async (req, res) => {
   try {
-    await handler(req, res)
+    await requestHandler(req, res)
   } catch (err) {
     console.error(err);
     res.statusCode = 500
@@ -25,6 +26,10 @@
 })
 const currentPort = parseInt(process.env.PORT, 10) || 3000
 
+server.on('upgrade', (req, socket, upgrade) => {
+  upgradeHandler(req, socket, upgrade)
+})
+
 server.listen(currentPort, (err) => {
   if (err) {
     console.error("Failed to start server", err)
@@ -38,7 +43,9 @@
     customServer: false,
     conf: {"env":{},"webpack":null,"webpackDevMiddleware":null,"eslint":{"ignoreDuringBuilds":false},"typescript":{"ignoreBuildErrors":false,"tsconfigPath":"tsconfig.json"},"distDir":"./.next","cleanDistDir":true,"assetPrefix":"","configOrigin":"next.config.js","useFileSystemPublicRoutes":true,"generateEtags":true,"pageExtensions":["tsx","ts","jsx","js"],"target":"server","poweredByHeader":true,"compress":true,"analyticsId":"","images":{"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","loaderFile":"","domains":[],"disableStaticImages":false,"minimumCacheTTL":60,"formats":["image/webp"],"dangerouslyAllowSVG":false,"contentSecurityPolicy":"script-src 'none'; frame-src 'none'; sandbox;","remotePatterns":[],"unoptimized":false},"devIndicators":{"buildActivity":true,"buildActivityPosition":"bottom-right"},"onDemandEntries":{"maxInactiveAge":15000,"pagesBufferLength":2},"amp":{"canonicalBase":""},"basePath":"","sassOptions":{},"trailingSlash":false,"i18n":null,"productionBrowserSourceMaps":false,"optimizeFonts":true,"excludeDefaultMomentLocales":true,"serverRuntimeConfig":{},"publicRuntimeConfig":{},"reactStrictMode":true,"httpAgentOptions":{"keepAlive":true},"outputFileTracing":true,"staticPageGenerationTimeout":60,"swcMinify":true,"output":"standalone","experimental":{"fetchCache":false,"middlewarePrefetch":"flexible","optimisticClientCache":true,"manualClientBasePath":false,"legacyBrowsers":false,"newNextLinkBehavior":true,"cpus":7,"sharedPool":true,"profiling":false,"isrFlushToDisk":true,"workerThreads":false,"pageEnv":false,"optimizeCss":false,"nextScriptWorkers":false,"scrollRestoration":false,"externalDir":false,"disableOptimizedLoading":false,"gzipSize":true,"swcFileReading":true,"craCompat":false,"esmExternals":true,"appDir":false,"isrMemoryCacheSize":52428800,"fullySpecified":false,"outputFileTracingRoot":"","swcTraceProfiling":false,"forceSwcTransforms":false,"largePageDataBytes":128000,"enableUndici":false,"adjustFontFallbacks":false,"adjustFontFallbacksWithSizeAdjust":false,"trustHostHeader":false},"configFileName":"next.config.js"},
   })
-  handler = nextServer.getRequestHandler()
+
+  requestHandler = nextServer.getRequestHandler()
+  upgradeHandler = nextServer.handleUpgrade.bind(nextServer)
 
   console.log(
     'Listening on port',

I based this off the startServer function used by the next start CLI.

@amorey
Copy link

amorey commented Jul 21, 2023

@georgeclaghorn Have you submitted a PR? It would be useful to get this fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Issue was opened via the bug report template.
Projects
None yet
Development

No branches or pull requests

2 participants