Skip to content

ERR_STREAM_WRITE_AFTER_END #21

@aaaaahaaaaa

Description

@aaaaahaaaaa

First of all: nice lib. AFAICT it's the only clean middleware out there that allows to update the request's headers with NextJS without errors.

I do encounter issues with your middleware though.

I have a fairly simple proxy setup for an API with a dynamic route (using SWR on the client side):

import type { NextApiRequest, NextApiResponse } from 'next'
import jwt from 'next-auth/jwt'
import httpProxyMiddleware from 'next-http-proxy-middleware';

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { accessToken } = await jwt.getToken({ req: req, secret: "CHANGE_ME" })
  return httpProxyMiddleware(req, res, {
    target: 'https://whatever.com',
    pathRewrite: { "^/before": '/after' },
    headers: { Authorization: `Bearer ${accessToken}` },
  })
}

When sending requests via to the proxy for with the same path, it works nicely. When requests with different paths go through the middleware, I see the following error (not right away, after a couple of minutes):

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (node:internal/errors:278:15)
    at write_ (node:_http_outgoing:718:11)
    at ClientRequest.write (node:_http_outgoing:677:15)
    at ProxyServer.<anonymous> (.../next-http-proxy-middleware/build/index.js:1:2419)
    at ProxyServer.emit (.../eventemitter3/index.js:210:27)
    at ClientRequest.<anonymous> (.../http-proxy/lib/http-proxy/passes/web-incoming.js:133:16)
    at ClientRequest.emit (node:events:388:22)
    at tickOnSocket (node:_http_client:781:7)
    at onSocketNT (node:_http_client:820:5)
    at processTicksAndRejections (node:internal/process/task_queues:81:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}

And prior to that, NextJS's server shows this kind of warning:

[...]
API resolved without sending a response for some/target/url, this may result in stalled requests
[...]

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomers

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions