Skip to content

Nextjs app router: state is reset each request #101

Description

@gussmith23

Love the package! Once I got it working, it's a very clean way of doing SSE.

I followed your example for NextJS with the App Router and found that it didn't work as the state I wanted persisted (namely, the Channel) wasn't being kept around. I'm not sure how NextJS works internally, so I have to assume this is expected (though not expected to a newbie) behavior.

I got around it with:

let channel: Channel;

// This fixes the issue of channel being reset on every request. I don't
// know how to do this more reasonably.
// https://github.com/vercel/next.js/discussions/48427#discussioncomment-10550280
if (process.env.NODE_ENV === "production") {
  channel = new Channel();
} else {
  // @ts-ignore
  if (!(global).channel) {
    // @ts-ignore
    global.channel = new Channel();
  }
  // @ts-ignore
  channel = global.channel;
}

Is this a known issue/pattern? Should this be documented in the examples, or is there a cleaner way around this on my side?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions