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

route sends headers before async onBeforeLoad event handler resolves #2837

Open
ondrejvelisek opened this issue Nov 23, 2024 · 0 comments
Open

Comments

@ondrejvelisek
Copy link

Which project does this relate to?

Start

Describe the bug

I want to log every page view to some external storage.

Instead of copy-pasting logging event to every route, I found pretty handy to use router event emminting. It supports "onBeforeLoad" event. Which is called on every page transition.

Code:

export function createRouter() {
  const queryClient = new QueryClient();

  const router = createTanStackRouter({
    routeTree,
    context: { queryClient },
    defaultPreload: "intent",
  });

  router.subscribe("onBeforeLoad", async ({ toLocation }) => {
    await logEvent({ data: { type: "page-view", page: toLocation.pathname } });
  });

  return routerWithQueryClient(router, queryClient);
}

the problem is, the logEvent is a server function and it tryies to set a set-cookie header.
import { setCookie } from "vinxi/http";

But it seems page route does not wait for those subscribe events. And starts to stream response right away. So Im getting:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

If you think there is a better place for loggin, Im happily listening.

Your Example Website or App

https://github.com/ondrejvelisek/peoples-budget/blob/main/app/router.tsx

Steps to Reproduce the Bug or Issue

  1. take TanStart basic example
  2. add router onBeforeLoad event handler
  3. call server function with setCookie from it
  4. run devserver and access any page
  5. dev server crashes with error

Expected behavior

Page route should wait for asynchronous subscribed event handlers.

Screenshots or Videos

Image

Platform

  • OS: macOS
  • Browser: Chrome
  • Version: -

Additional context

It worked in "@tanstack/start": "^1.73.1" but not working in "@tanstack/start": "^1.82.6".

The bug is on Node but not see it on Bun.

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

1 participant