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

ERR_STREAM_WRITE_AFTER_END #21

Closed
aaaaahaaaaa opened this issue Mar 24, 2021 · 10 comments
Closed

ERR_STREAM_WRITE_AFTER_END #21

aaaaahaaaaa opened this issue Mar 24, 2021 · 10 comments
Labels
bug Something isn't working good first issue Good for newcomers

Comments

@aaaaahaaaaa
Copy link

aaaaahaaaaa commented Mar 24, 2021

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
[...]
@stegano
Copy link
Owner

stegano commented Mar 28, 2021

Hi @aaaaahaaaaa,
Thanks for your reporting 😀
Could you let me know your code snippet of making request
(or HTTP request packets captured using tcpdump)

@stegano stegano added the good first issue Good for newcomers label Mar 28, 2021
@FDiskas
Copy link

FDiskas commented Apr 7, 2021

Try like so

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" })
  await httpProxyMiddleware(req, res, {
    target: 'https://whatever.com',
    pathRewrite: { "^/before": '/after' },
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  res.end();
}

The main problem is that response is not finished

@FDiskas
Copy link

FDiskas commented Apr 14, 2021

Related vercel/next.js#10439

@aaaaahaaaaa
Copy link
Author

aaaaahaaaaa commented Apr 15, 2021

Thanks for the feedback. Unfortunately I changed my implementation and have no means to test this at the moment. I'll try again when I have a minute. I'll close this issue for now.

@stegano
Copy link
Owner

stegano commented Apr 16, 2021

This issue may have been resolved by #24.

@stegano stegano added the bug Something isn't working label Apr 16, 2021
@FDiskas
Copy link

FDiskas commented Apr 22, 2021

v^1.0.10 - still getting

this may result in stalled requests.

import httpProxyMiddleware from 'next-http-proxy-middleware';
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from '@auth0/nextjs-auth0';
import * as Sentry from '@sentry/node';

import { initSentry } from 'src/utils/sentry';

export default async (req: NextApiRequest, res: NextApiResponse) =>
    httpProxyMiddleware(req, res, {
        target: process.env.NEXT_PUBLIC_API_BASE_URL,
        // In addition, you can use the `pathRewrite` option provided by `next-http-proxy`
        pathRewrite: {
            '^/api/rest': '/api',
        },
        headers: {
            Authorization: `Bearer ${getSession(req, res)?.idToken}`,
            'Content-Type': 'application/json-patch+json',
        },
    }).catch(async (error) => {
        initSentry();

        Sentry.captureException(error);

        await Sentry.flush(2000);
    });

if I add res.end() then after some time I get

http-proxy/lib/http-proxy/index.js:120
    throw err;
    ^

Error: socket hang up
    at connResetException (internal/errors.js:617:14)
    at TLSSocket.socketCloseListener (_http_client.js:443:25)
    at TLSSocket.emit (events.js:327:22)
    at TLSSocket.EventEmitter.emit (domain.js:486:12)
    at net.js:673:12
    at TCP.done (_tls_wrap.js:563:7) {
  code: 'ECONNRESET'

@FDiskas FDiskas mentioned this issue Apr 25, 2021
@OliverDudgeon
Copy link

Also getting API resolved without sending a response for some/target/url, this may result in stalled requests type issues with a similar setup.

@FDiskas
Copy link

FDiskas commented May 27, 2021

I added

export​ ​const​ ​config​ ​=​ ​{​
    ​api​: ​{​
        ​bodyParser​: ​false​,​
        ​externalResolver​: ​true​,​
    ​}​,​
​}​;​

On top of file and thous errors is not displayed anymore, but not sure is the problem is solved that way

@stegano
Copy link
Owner

stegano commented Feb 13, 2022

@all-contributors please add @FDiskas for doc

@allcontributors
Copy link
Contributor

@stegano

I've put up a pull request to add @FDiskas! 🎉

warren-sadler added a commit to Therify/directory that referenced this issue Feb 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

4 participants