Next.js Discord

Discord Forum

How to replicate http-proxy-middleware options in Next 14

Unanswered
Singapura posted this in #help-forum
Open in Discord
Avatar
SingapuraOP
I'm attempting to upgrade an ecommerce application from Next 12 to Next 14. I'm trying to get rid of a custom server but running into problems with proxy endpoints. Most npm packages don't work with the App Router:
https://github.com/chimurai/http-proxy-middleware/issues/932
https://github.com/stegano/next-http-proxy-middleware/issues/83

Our app currently uses http-proxy-middleware. Here is an example of an endpoint:
  server.use(
    '/cms',
    proxy('/cms', {
      logLevel: 'debug',
      target: getCMSUrl(),
      xfwd: true,
      changeOrigin: true,
      prependPath: false,
      pathRewrite: { '^/cms': '/cms' }, // Note: This needs to be modified if we move CMS locations
      onProxyRes: function OnProxyRes (proxyRes, req, res) {
        // Capture the response from the backend and check if response is being chunked
        var chunked = /chunked/.test(proxyRes.headers['transfer-encoding'])
        if (chunked) {
          delete proxyRes.headers['transfer-encoding']
          // If chunked, then gather all chunks and pass it on unchunked. Remove transfer-encoding header.
          res.write = (function (override) {
            return function (chunk, encoding, callback) {
              override.call(res, chunk, 'binary', callback)
            }
          })(res.write)

          res.end = (function (override) {
            return function (chunk, encoding, callback) {
              override.call(res, chunk, 'binary', callback)
            }
          })(res.end)
        }
      }
    })
  )

In Next 14/App Router, the "official" proxy approaches involve rewrites, middleware, and/or route handlers. It's unclear whether any of those offer the same functionality as the npm packages. Using NextResponse in middleware seems like it could possibly work. Route handlers don't seem to have the externalResolver flag like in /pages, is this available in App Router?

0 Replies