Skip to content

Context is still empty when running the head() function. #4889

@zugzwangm

Description

@zugzwangm

Which project does this relate to?

Router

Describe the bug

If you add something to the context via beforeLoad(), it will not be available inside head() after a full-page reload (F5). It will only be available after subsequent navigations (via <Link> for example).

Example

// routes/(app)/index.tsx
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/(app)/")({
  beforeLoad: () => {
    return {
      getTitle: () => `Home`,
    };
  },
  component: Index,
});

function Index() {
  return (
    <h3>Welcome Home!</h3>
  );
}
// routes/__root.tsx
interface MyRouterContext {
  getTitle?: () => string;
  queryClient: QueryClient;
}

export const Route = createRootRouteWithContext<MyRouterContext>()({
  head: ({ matches }) => {
    const title = matches
      .filter((match) => match.context.getTitle)
      .reduce((acc, { context }) => {
        const title = context.getTitle!();
        return acc ? `${acc} - ${title}` : title;
      }, "");

    return {
      meta: [
        {
          title: `${title}`, // will be empty on a full-page reload
        },
      ],
    };
  },
  component: RootComponent,
});

function RootComponent() {
  return (
    <>
      <HeadContent />
      <Outlet />
      <Scripts />
      <TanStackRouterDevtools position="bottom-right" />
    </>
  );
}

Your Example Website or App

https://nbwiowazwkgithub-athu--3000--96435430.local-credentialless.webcontainer.io/

Steps to Reproduce the Bug or Issue

Create a simple project and use the code given in the example.
Notice the page title isn't set to "Home" on a full-page reload.

Expected behavior

In the given example, I expected the page title to be set to "Home" after a full-page reload (F5).

Screenshots or Videos

No response

Platform

{
  "dependencies": {
    "@tanstack/react-router": "^1.130.12",
    "@tanstack/react-router-devtools": "^1.130.13",
    "react": "^19.1.0",
    "react-dom": "^19.1.0",
  },
}

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions