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

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client #1

Open
juicecultus opened this issue Aug 6, 2020 · 6 comments

Comments

@juicecultus
Copy link

juicecultus commented Aug 6, 2020

Hi Scott @Hendrixer

When I fetch one note in /pages/notes/[id].js the app crashes with the follwoing error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:536:11)
    at DevServer.sendHTML (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/server/next-dev-server.js:31:5)
    at DevServer.render (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:56:37)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async Object.fn (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:32:107)
    at async Router.execute (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/router.js:38:67)
    at async DevServer.run (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:49:494)
    at async DevServer.handleRequest (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:18:101) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
events.js:291
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at writeAfterEnd (_http_outgoing.js:646:15)
    at ServerResponse.end (_http_outgoing.js:766:7)
    at ServerResponse.end (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/compiled/compression/index.js:1:148805)
    at DevServer.handleRequest (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:18:189)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
Emitted 'error' event on ServerResponse instance at:
    at writeAfterEndNT (_http_outgoing.js:705:7)
    at processTicksAndRejections (internal/process/task_queues.js:81:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

This is my code for /pages/notes/[id].js:

/** @jsx jsx */
import { jsx } from 'theme-ui';
import { useRouter } from 'next/router';
import Link from 'next/link';

const DynamicPage = ({ note }) => {
  return (
    <div sx={{ variant: 'containers.page' }}>
      <h1>Note: {note.title} </h1>
    </div>
  );
};

export default DynamicPage;

export async function getServerSideProps({ params, req, res }) {
  const response = await fetch(`http://localhost:3000/api/notes/${params.id}`);

  // so much power!
  if (!response.ok) {
    res.writeHead(302, { Location: '/notes' });
    res.end();
    return { props: {} };
  }

  const { data } = await response.json();

  if (data) {
    return {
      props: { note: data },
    };
  }
}

NOTE: only difference I have from your repo is named exports, my API is at API/notes & my components and data are in root.

A console.log(response) shows:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kTransformState)]: [Object]
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'http://localhost:3000/api/notes/1596709251707',
    status: 404,
    statusText: 'Not Found',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

Steps to trigger the error - follow this path:

  1. yarn dev -- OK
  2. go to localhost:3000 -- OK
  3. click Notes in Nav bar -- OK
  4. click any Note -- error (status 404 - not found)

Steps to avoid error:

  1. yarn dev -- OK
  2. go to localhost: 3000 -- OK
  3. go to http://localhost:3000/api/notes/{id from step 4 above}
    But as soon as you click Notes in Nav bar then you're in trouble again.

Looks like new IDs are generated and somehow headers cannot be updated anymore.

@lancemccluskey
Copy link

lancemccluskey commented Aug 21, 2020

I am getting this error too. I was able to fix it by adding `typeof window === 'undefined' to the conditional expression with writeHead. Now it looks like this:

  if (!response.ok && typeof window === 'undefined') {
    res.writeHead(302, { Location: '/notes' })
    res.end()
    return {props: {}}
  }

I am honestly now positive why you need this though.
@juicecultus

@aashiqahmed98
Copy link

Instead of strict equality (===) operator use Object,is() and le me know!

@slavo3dev
Copy link

I had a similar issue, but I was trying to do all with ts. When I convert all to js everything was working as should be

@armor009
Copy link

armor009 commented Jun 7, 2021

Can anyone explain what exactly is happening here?
This seems to cover intricacies of next.js and server responses.

@JasonNoonan
Copy link

Having the same error. However, if I log params as the first line of getServerSideProps, the function works. Some kind of timing issue where params is not ready when fetch tries to call it, maybe?

export async function getServerSideProps({params, req, res}) {
  console.log(params)
  const response = await fetch(`http://localhost:3000/api/note/${params.id}`)

  if (!response.ok) {
    res.writeHead(302, { Location: '/notes' })
    res.end()
    return {props: {}}
  }

  const {data} = await response.json()
  
  
  if (data) {
    return {
      props: {note: data}
    }
  }
}```

@BhumilModi
Copy link

try this it worked for me
export async function getServerSideProps({ params, req, res }) {
const response = await fetch(http://localhost:3000/api/note/${params.id});

if (!response.ok) {
return res.writeHead(302, { Location: "/notes" }).end();
}

const { data } = await response.json();

if (data) {
return {
props: { note: data },
};
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants