diff --git a/e2e/solid-start/basic-head/.gitignore b/e2e/solid-start/basic-head/.gitignore
new file mode 100644
index 0000000000..3684847062
--- /dev/null
+++ b/e2e/solid-start/basic-head/.gitignore
@@ -0,0 +1 @@
+/test-results/
\ No newline at end of file
diff --git a/e2e/solid-start/basic-head/package.json b/e2e/solid-start/basic-head/package.json
new file mode 100644
index 0000000000..1406c9f3da
--- /dev/null
+++ b/e2e/solid-start/basic-head/package.json
@@ -0,0 +1,43 @@
+{
+ "name": "tanstack-solid-start-e2e-basic-head",
+ "private": true,
+ "sideEffects": false,
+ "type": "module",
+ "scripts": {
+ "dev": "vite dev --port 3000",
+ "dev:e2e": "vite dev",
+ "build": "vite build && tsc --noEmit",
+ "build:spa": "MODE=spa vite build && tsc --noEmit",
+ "build:prerender": "MODE=prerender vite build && tsc --noEmit",
+ "preview": "vite preview",
+ "start": "pnpm exec srvx --prod -s ../client dist/server/server.js",
+ "start:spa": "node server.js",
+ "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' &",
+ "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'",
+ "test:e2e:spaMode": "rm -rf port*.txt; MODE=spa playwright test --project=chromium",
+ "test:e2e:ssrMode": "rm -rf port*.txt; playwright test --project=chromium",
+ "test:e2e:prerender": "rm -rf port*.txt; MODE=prerender playwright test --project=chromium",
+ "test:e2e:preview": "rm -rf port*.txt; MODE=preview playwright test --project=chromium",
+ "test:e2e": "pnpm run test:e2e:spaMode && pnpm run test:e2e:ssrMode && pnpm run test:e2e:prerender && pnpm run test:e2e:preview"
+ },
+ "dependencies": {
+ "@tanstack/solid-router": "workspace:^",
+ "@tanstack/solid-router-devtools": "workspace:^",
+ "@tanstack/solid-start": "workspace:^",
+ "express": "^5.1.0",
+ "http-proxy-middleware": "^3.0.5",
+ "solid-js": "^1.9.10",
+ "vite": "^7.1.7"
+ },
+ "devDependencies": {
+ "@playwright/test": "^1.50.1",
+ "@tailwindcss/vite": "^4.1.18",
+ "@tanstack/router-e2e-utils": "workspace:^",
+ "@types/node": "^22.10.2",
+ "srvx": "^0.9.8",
+ "tailwindcss": "^4.1.18",
+ "typescript": "^5.7.2",
+ "vite-plugin-solid": "^2.11.10",
+ "vite-tsconfig-paths": "^5.1.4"
+ }
+}
diff --git a/e2e/solid-start/basic-head/playwright.config.ts b/e2e/solid-start/basic-head/playwright.config.ts
new file mode 100644
index 0000000000..aa29067f46
--- /dev/null
+++ b/e2e/solid-start/basic-head/playwright.config.ts
@@ -0,0 +1,72 @@
+import { defineConfig, devices } from '@playwright/test'
+import {
+ getDummyServerPort,
+ getTestServerPort,
+} from '@tanstack/router-e2e-utils'
+import { isSpaMode } from './tests/utils/isSpaMode'
+import { isPrerender } from './tests/utils/isPrerender'
+import { isPreview } from './tests/utils/isPreview'
+import packageJson from './package.json' with { type: 'json' }
+
+const PORT = await getTestServerPort(
+ `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`,
+)
+const START_PORT = await getTestServerPort(
+ `${packageJson.name}${isSpaMode ? '_spa_start' : ''}`,
+)
+const EXTERNAL_PORT = await getDummyServerPort(packageJson.name)
+const baseURL = `http://localhost:${PORT}`
+const spaModeCommand = `pnpm build:spa && pnpm start:spa`
+const ssrModeCommand = `pnpm build && pnpm start`
+const prerenderModeCommand = `pnpm run test:e2e:startDummyServer && pnpm build:prerender && pnpm run test:e2e:stopDummyServer && pnpm start`
+const previewModeCommand = `pnpm build && pnpm preview --port ${PORT}`
+
+const getCommand = () => {
+ if (isSpaMode) return spaModeCommand
+ if (isPrerender) return prerenderModeCommand
+ if (isPreview) return previewModeCommand
+ return ssrModeCommand
+}
+console.log('running in spa mode: ', isSpaMode.toString())
+console.log('running in prerender mode: ', isPrerender.toString())
+console.log('running in preview mode: ', isPreview.toString())
+/**
+ * See https://playwright.dev/docs/test-configuration.
+ */
+export default defineConfig({
+ testDir: './tests',
+ workers: 1,
+ reporter: [['line']],
+
+ globalSetup: './tests/setup/global.setup.ts',
+ globalTeardown: './tests/setup/global.teardown.ts',
+
+ use: {
+ /* Base URL to use in actions like `await page.goto('/')`. */
+ baseURL,
+ },
+
+ webServer: {
+ command: getCommand(),
+ url: baseURL,
+ reuseExistingServer: !process.env.CI,
+ stdout: 'pipe',
+ env: {
+ MODE: process.env.MODE || '',
+ VITE_NODE_ENV: 'test',
+ VITE_EXTERNAL_PORT: String(EXTERNAL_PORT),
+ VITE_SERVER_PORT: String(PORT),
+ START_PORT: String(START_PORT),
+ PORT: String(PORT),
+ },
+ },
+
+ projects: [
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ },
+ },
+ ],
+})
diff --git a/e2e/solid-start/basic-head/public/favicon.ico b/e2e/solid-start/basic-head/public/favicon.ico
new file mode 100644
index 0000000000..1a1751676f
Binary files /dev/null and b/e2e/solid-start/basic-head/public/favicon.ico differ
diff --git a/e2e/solid-start/basic-head/server.js b/e2e/solid-start/basic-head/server.js
new file mode 100644
index 0000000000..d618ab4bce
--- /dev/null
+++ b/e2e/solid-start/basic-head/server.js
@@ -0,0 +1,67 @@
+import { toNodeHandler } from 'srvx/node'
+import path from 'node:path'
+import express from 'express'
+import { createProxyMiddleware } from 'http-proxy-middleware'
+
+const port = process.env.PORT || 3000
+
+const startPort = process.env.START_PORT || 3001
+
+export async function createStartServer() {
+ const server = (await import('./dist/server/server.js')).default
+ const nodeHandler = toNodeHandler(server.fetch)
+
+ const app = express()
+
+ app.use(express.static('./dist/client'))
+
+ app.use(async (req, res, next) => {
+ try {
+ await nodeHandler(req, res)
+ } catch (error) {
+ next(error)
+ }
+ })
+
+ return { app }
+}
+
+export async function createSpaServer() {
+ const app = express()
+
+ app.use(
+ '/api',
+ createProxyMiddleware({
+ target: `http://localhost:${startPort}/api`, // Replace with your target server's URL
+ changeOrigin: false, // Needed for virtual hosted sites,
+ }),
+ )
+
+ app.use(
+ '/_serverFn',
+ createProxyMiddleware({
+ target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL
+ changeOrigin: false, // Needed for virtual hosted sites,
+ }),
+ )
+
+ app.use(express.static('./dist/client'))
+
+ app.get('/{*splat}', (req, res) => {
+ res.sendFile(path.resolve('./dist/client/index.html'))
+ })
+
+ return { app }
+}
+
+createSpaServer().then(async ({ app }) =>
+ app.listen(port, () => {
+ console.info(`Client Server: http://localhost:${port}`)
+ }),
+)
+
+createStartServer().then(async ({ app }) =>
+ app.listen(startPort, () => {
+ console.info(`Start Server: http://localhost:${startPort}`)
+ }),
+)
diff --git a/e2e/solid-start/basic-head/src/client.tsx b/e2e/solid-start/basic-head/src/client.tsx
new file mode 100644
index 0000000000..0e10259d30
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/client.tsx
@@ -0,0 +1,10 @@
+// DO NOT DELETE THIS FILE!!!
+// This file is a good smoke test to make sure the custom client entry is working
+import { hydrate } from 'solid-js/web'
+import { StartClient, hydrateStart } from '@tanstack/solid-start/client'
+
+console.log("[client-entry]: using custom client entry in 'src/client.tsx'")
+
+hydrateStart().then((router) => {
+ hydrate(() => , document)
+})
diff --git a/e2e/solid-start/basic-head/src/components/DefaultCatchBoundary.tsx b/e2e/solid-start/basic-head/src/components/DefaultCatchBoundary.tsx
new file mode 100644
index 0000000000..5556992f48
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/components/DefaultCatchBoundary.tsx
@@ -0,0 +1,51 @@
+import {
+ ErrorComponent,
+ Link,
+ rootRouteId,
+ useMatch,
+ useRouter,
+} from '@tanstack/solid-router'
+import type { ErrorComponentProps } from '@tanstack/solid-router'
+
+export function DefaultCatchBoundary({ error }: ErrorComponentProps) {
+ const router = useRouter()
+ const isRoot = useMatch({
+ strict: false,
+ select: (state) => state.id === rootRouteId,
+ })
+
+ console.error(error)
+
+ return (
+
+
+
+
+ {isRoot() ? (
+
+ Home
+
+ ) : (
+
+ )}
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-head/src/components/NotFound.tsx b/e2e/solid-start/basic-head/src/components/NotFound.tsx
new file mode 100644
index 0000000000..c48444862b
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/components/NotFound.tsx
@@ -0,0 +1,25 @@
+import { Link } from '@tanstack/solid-router'
+
+export function NotFound({ children }: { children?: any }) {
+ return (
+
+
+ {children ||
The page you are looking for does not exist.
}
+
+
+
+
+ Start Over
+
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-head/src/routeTree.gen.ts b/e2e/solid-start/basic-head/src/routeTree.gen.ts
new file mode 100644
index 0000000000..a7a7067f15
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/routeTree.gen.ts
@@ -0,0 +1,86 @@
+/* eslint-disable */
+
+// @ts-nocheck
+
+// noinspection JSUnusedGlobalSymbols
+
+// This file was automatically generated by TanStack Router.
+// You should NOT make any changes in this file as it will be overwritten.
+// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
+
+import { Route as rootRouteImport } from './routes/__root'
+import { Route as IndexRouteImport } from './routes/index'
+import { Route as ArticleIdRouteImport } from './routes/article.$id'
+
+const IndexRoute = IndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const ArticleIdRoute = ArticleIdRouteImport.update({
+ id: '/article/$id',
+ path: '/article/$id',
+ getParentRoute: () => rootRouteImport,
+} as any)
+
+export interface FileRoutesByFullPath {
+ '/': typeof IndexRoute
+ '/article/$id': typeof ArticleIdRoute
+}
+export interface FileRoutesByTo {
+ '/': typeof IndexRoute
+ '/article/$id': typeof ArticleIdRoute
+}
+export interface FileRoutesById {
+ __root__: typeof rootRouteImport
+ '/': typeof IndexRoute
+ '/article/$id': typeof ArticleIdRoute
+}
+export interface FileRouteTypes {
+ fileRoutesByFullPath: FileRoutesByFullPath
+ fullPaths: '/' | '/article/$id'
+ fileRoutesByTo: FileRoutesByTo
+ to: '/' | '/article/$id'
+ id: '__root__' | '/' | '/article/$id'
+ fileRoutesById: FileRoutesById
+}
+export interface RootRouteChildren {
+ IndexRoute: typeof IndexRoute
+ ArticleIdRoute: typeof ArticleIdRoute
+}
+
+declare module '@tanstack/solid-router' {
+ interface FileRoutesByPath {
+ '/': {
+ id: '/'
+ path: '/'
+ fullPath: '/'
+ preLoaderRoute: typeof IndexRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/article/$id': {
+ id: '/article/$id'
+ path: '/article/$id'
+ fullPath: '/article/$id'
+ preLoaderRoute: typeof ArticleIdRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ }
+}
+
+const rootRouteChildren: RootRouteChildren = {
+ IndexRoute: IndexRoute,
+ ArticleIdRoute: ArticleIdRoute,
+}
+export const routeTree = rootRouteImport
+ ._addFileChildren(rootRouteChildren)
+ ._addFileTypes()
+
+import type { getRouter } from './router.tsx'
+import type { createStart } from '@tanstack/solid-start'
+declare module '@tanstack/solid-start' {
+ interface Register {
+ ssr: true
+ router: Awaited>
+ }
+}
diff --git a/e2e/solid-start/basic-head/src/router.tsx b/e2e/solid-start/basic-head/src/router.tsx
new file mode 100644
index 0000000000..fe71435a4e
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/router.tsx
@@ -0,0 +1,16 @@
+import { createRouter } from '@tanstack/solid-router'
+import { routeTree } from './routeTree.gen'
+import { DefaultCatchBoundary } from './components/DefaultCatchBoundary'
+import { NotFound } from './components/NotFound'
+
+export function getRouter() {
+ const router = createRouter({
+ routeTree,
+ // defaultPreload: 'intent',
+ defaultErrorComponent: DefaultCatchBoundary,
+ defaultNotFoundComponent: () => ,
+ scrollRestoration: true,
+ })
+
+ return router
+}
diff --git a/e2e/solid-start/basic-head/src/routes/__root.tsx b/e2e/solid-start/basic-head/src/routes/__root.tsx
new file mode 100644
index 0000000000..7275135e1f
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/routes/__root.tsx
@@ -0,0 +1,83 @@
+///
+import {
+ HeadContent,
+ Link,
+ Outlet,
+ Scripts,
+ createRootRoute,
+} from '@tanstack/solid-router'
+
+import { TanStackRouterDevtoolsInProd } from '@tanstack/solid-router-devtools'
+import { HydrationScript } from 'solid-js/web'
+import { NotFound } from '~/components/NotFound'
+import tailwindCssUrl from '~/tailwind.css?url'
+
+export const Route = createRootRoute({
+ head: () => ({
+ meta: [
+ {
+ name: 'viewport',
+ content: 'width=device-width, initial-scale=1',
+ },
+ {
+ title: 'TanStack Router Head Function Test',
+ },
+ {
+ name: 'description',
+ content: 'Testing head() function behavior with async loaders',
+ },
+ ],
+ links: [
+ { rel: 'icon', href: '/favicon.ico' },
+ { rel: 'stylesheet', href: tailwindCssUrl },
+ ],
+ }),
+ errorComponent: (props) => {props.error.stack}
,
+ notFoundComponent: () => ,
+ component: RootComponent,
+})
+
+function RootComponent() {
+ return (
+
+
+
+
+
+
+
+
+ Home
+ {' '}
+
+ Article 1
+ {' '}
+
+ Article 2
+
+
+
+
+
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-head/src/routes/article.$id.tsx b/e2e/solid-start/basic-head/src/routes/article.$id.tsx
new file mode 100644
index 0000000000..f470297370
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/routes/article.$id.tsx
@@ -0,0 +1,85 @@
+import { createFileRoute, useRouter } from '@tanstack/solid-router'
+import { createSignal, Show } from 'solid-js'
+import { fakeLogin, fakeLogout, isAuthed } from '~/utils/fake-auth'
+
+const fetchArticle = async (id: string) => {
+ await new Promise((resolve) => setTimeout(resolve, 1000))
+ return isAuthed()
+ ? {
+ title: `Article Title for ${id}`,
+ content: `Article content for ${id}\n`.repeat(10),
+ }
+ : null
+}
+
+export const Route = createFileRoute('/article/$id')({
+ ssr: false, // isAuthed is ClientOnly
+ loader: async ({ params }) => {
+ const article = await fetchArticle(params.id)
+ return article
+ },
+ head: ({ loaderData }) => {
+ const title = loaderData?.title ?? 'title n/a'
+ console.log('[head] Setting title:', title)
+ return {
+ meta: [{ title }],
+ }
+ },
+ component: RouteComponent,
+})
+
+function RouteComponent() {
+ const data = Route.useLoaderData()
+
+ return (
+ <>
+
+ Article Not Accessible.}>
+ {(article) => {article().content}
}
+
+ >
+ )
+}
+
+function AuthStatus() {
+ const router = useRouter()
+
+ const [auth, setAuth] = createSignal(isAuthed())
+
+ return (
+
+ Not authenticated
+
+
+ }
+ >
+
+
You're authenticated!
+
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-head/src/routes/index.tsx b/e2e/solid-start/basic-head/src/routes/index.tsx
new file mode 100644
index 0000000000..e737205fbc
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/routes/index.tsx
@@ -0,0 +1,25 @@
+import { Link, createFileRoute } from '@tanstack/solid-router'
+
+export const Route = createFileRoute('/')({
+ component: Home,
+})
+
+function Home() {
+ return (
+
+
Welcome to Head Function Test Suite
+
+ This test suite validates head() function behavior with async loaders.
+
+
+
+ Go to Article 1
+
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-head/src/server.ts b/e2e/solid-start/basic-head/src/server.ts
new file mode 100644
index 0000000000..d48e6df349
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/server.ts
@@ -0,0 +1,11 @@
+// DO NOT DELETE THIS FILE!!!
+// This file is a good smoke test to make sure the custom server entry is working
+import handler from '@tanstack/solid-start/server-entry'
+
+console.log("[server-entry]: using custom server entry in 'src/server.ts'")
+
+export default {
+ fetch(request: Request) {
+ return handler.fetch(request)
+ },
+}
diff --git a/e2e/solid-start/basic-head/src/tailwind.css b/e2e/solid-start/basic-head/src/tailwind.css
new file mode 100644
index 0000000000..d4b5078586
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/tailwind.css
@@ -0,0 +1 @@
+@import 'tailwindcss';
diff --git a/e2e/solid-start/basic-head/src/utils/fake-auth.ts b/e2e/solid-start/basic-head/src/utils/fake-auth.ts
new file mode 100644
index 0000000000..3c75b3287f
--- /dev/null
+++ b/e2e/solid-start/basic-head/src/utils/fake-auth.ts
@@ -0,0 +1,16 @@
+import { createClientOnlyFn } from '@tanstack/solid-start'
+
+export { fakeLogin, fakeLogout, isAuthed }
+
+const isAuthed = createClientOnlyFn(() => {
+ const tokenValue = localStorage.getItem('auth')
+ return tokenValue === 'good'
+})
+
+const fakeLogin = createClientOnlyFn(() => {
+ localStorage.setItem('auth', 'good')
+})
+
+const fakeLogout = createClientOnlyFn(() => {
+ localStorage.removeItem('auth')
+})
diff --git a/e2e/solid-start/basic-head/tests/head.spec.ts b/e2e/solid-start/basic-head/tests/head.spec.ts
new file mode 100644
index 0000000000..ff4bded503
--- /dev/null
+++ b/e2e/solid-start/basic-head/tests/head.spec.ts
@@ -0,0 +1,175 @@
+import { expect } from '@playwright/test'
+import { test } from '@tanstack/router-e2e-utils'
+import { isSpaMode } from './utils/isSpaMode'
+import { isPreview } from './utils/isPreview'
+
+// Skip SPA and preview modes - routes with ssr:false don't execute head() in these modes
+test.skip(
+ isSpaMode || isPreview,
+ "Head function tests require SSR (ssr:false routes don't execute head() in SPA/preview)",
+)
+
+test.describe('head() function with async loaders', () => {
+ test.beforeEach(async ({ page }) => {
+ // Clear localStorage before each test
+ await page.goto('/')
+ await page.evaluate(() => localStorage.clear())
+ })
+
+ test('head() receives fresh loaderData after async loader completes', async ({
+ page,
+ }) => {
+ // Navigate to home and login
+ await page.goto('/')
+ await page.evaluate(() => localStorage.setItem('auth', 'good'))
+
+ // Navigate to article 1
+ await page.goto('/article/1')
+
+ // Wait for loader to complete and check title
+ await page.waitForTimeout(1500) // Wait for 1s loader + buffer
+ await expect(page).toHaveTitle('Article Title for 1')
+
+ // Verify content is shown
+ await expect(page.locator('text=Article content for 1')).toBeVisible()
+ })
+
+ test('stale head re-run aborts when navigation to different article happens', async ({
+ page,
+ }) => {
+ // Login first
+ await page.goto('/')
+ await page.evaluate(() => localStorage.setItem('auth', 'good'))
+
+ // Navigate to article 1 (async loader starts)
+ const nav1 = page.goto('/article/1')
+
+ // Immediately navigate to article 2 before article 1 loader completes
+ await page.waitForTimeout(100) // Small delay to ensure first nav started
+ await page.goto('/article/2')
+
+ // Wait for navigation to complete
+ await nav1.catch(() => {}) // First navigation might be cancelled
+
+ // Wait for article 2 loader to complete
+ await page.waitForTimeout(1500)
+
+ // Verify we're on article 2 with correct title (not polluted by article 1)
+ await expect(page).toHaveTitle('Article Title for 2')
+ await expect(page.locator('text=Article content for 2')).toBeVisible()
+
+ // Ensure article 1 content is not present
+ await expect(page.locator('text=Article content for 1')).not.toBeVisible()
+ })
+
+ test('stale head re-run aborts when route invalidation happens', async ({
+ page,
+ }) => {
+ // Capture head() execution logs to verify abort behavior
+ const headLogs: string[] = []
+ page.on('console', (msg) => {
+ const text = msg.text()
+ if (text.includes('[head] Setting title:')) {
+ headLogs.push(text)
+ }
+ })
+
+ // Setup: Login and navigate to article 1
+ await page.goto('/')
+ await page.evaluate(() => localStorage.setItem('auth', 'good'))
+ await page.goto('/article/1')
+ await page.waitForTimeout(1500)
+ await expect(page).toHaveTitle('Article Title for 1')
+
+ // Clear logs from initial navigation
+ headLogs.length = 0
+
+ // Trigger first invalidation: logout (loader returns null after 1s)
+ await page.click('button:has-text("Log out")')
+
+ // Trigger second invalidation immediately: login (before logout loader completes)
+ // This should abort the logout's head re-run via generation counter
+ await page.waitForTimeout(100)
+ await page.click('button:has-text("Log in")')
+
+ // Wait for both loaders to complete
+ await page.waitForTimeout(1500)
+
+ // Verify final state
+ await expect(page).toHaveTitle('Article Title for 1')
+ await expect(page.locator('text=Article content for 1')).toBeVisible()
+
+ // Critical assertion: If abort worked, "title n/a" should NEVER appear in logs
+ // Expected logs (if abort works):
+ // 1. "Article Title for 1" - logout's 1st head (stale data)
+ // 2. "Article Title for 1" - login's 1st head (stale data)
+ // 3. "Article Title for 1" - login's 2nd head (fresh data)
+ // If abort FAILED, logout's 2nd head would execute with null data:
+ // 4. "title n/a" - logout's 2nd head (SHOULD BE ABORTED)
+ expect(headLogs.join('\n')).not.toContain('title n/a')
+ expect(headLogs).toHaveLength(3)
+ })
+
+ test('head() shows fallback title when not authenticated', async ({
+ page,
+ }) => {
+ // Navigate without logging in
+ await page.goto('/article/1')
+
+ // Wait for loader to complete
+ await page.waitForTimeout(1500)
+
+ // Should show fallback title since loader returns null
+ await expect(page).toHaveTitle('title n/a')
+
+ // Should show not accessible message
+ await expect(page.locator('text=Article Not Accessible')).toBeVisible()
+ })
+
+ test('rapid navigation between articles shows correct final title', async ({
+ page,
+ }) => {
+ // Login
+ await page.goto('/')
+ await page.evaluate(() => localStorage.setItem('auth', 'good'))
+
+ // Rapidly navigate: 1 -> 2 -> 1 -> 2
+ await page.goto('/article/1')
+ await page.waitForTimeout(100)
+
+ await page.goto('/article/2')
+ await page.waitForTimeout(100)
+
+ await page.goto('/article/1')
+ await page.waitForTimeout(100)
+
+ await page.goto('/article/2')
+
+ // Wait for final loader to complete
+ await page.waitForTimeout(1500)
+
+ // Should show article 2 title (final navigation)
+ await expect(page).toHaveTitle('Article Title for 2')
+ await expect(page.locator('text=Article content for 2')).toBeVisible()
+ })
+
+ test('head() updates when using navigation links', async ({ page }) => {
+ // Login
+ await page.goto('/')
+ await page.evaluate(() => localStorage.setItem('auth', 'good'))
+
+ // Click Article 1 link
+ await page.click('a:has-text("Article 1")')
+ await page.waitForTimeout(1500)
+ await expect(page).toHaveTitle('Article Title for 1')
+
+ // Click Article 2 link
+ await page.click('a:has-text("Article 2")')
+ await page.waitForTimeout(1500)
+ await expect(page).toHaveTitle('Article Title for 2')
+
+ // Click Home link
+ await page.click('a:has-text("Home")')
+ await expect(page).toHaveTitle('TanStack Router Head Function Test')
+ })
+})
diff --git a/e2e/solid-start/basic-head/tests/setup/global.setup.ts b/e2e/solid-start/basic-head/tests/setup/global.setup.ts
new file mode 100644
index 0000000000..3593d10ab9
--- /dev/null
+++ b/e2e/solid-start/basic-head/tests/setup/global.setup.ts
@@ -0,0 +1,6 @@
+import { e2eStartDummyServer } from '@tanstack/router-e2e-utils'
+import packageJson from '../../package.json' with { type: 'json' }
+
+export default async function setup() {
+ await e2eStartDummyServer(packageJson.name)
+}
diff --git a/e2e/solid-start/basic-head/tests/setup/global.teardown.ts b/e2e/solid-start/basic-head/tests/setup/global.teardown.ts
new file mode 100644
index 0000000000..62fd79911c
--- /dev/null
+++ b/e2e/solid-start/basic-head/tests/setup/global.teardown.ts
@@ -0,0 +1,6 @@
+import { e2eStopDummyServer } from '@tanstack/router-e2e-utils'
+import packageJson from '../../package.json' with { type: 'json' }
+
+export default async function teardown() {
+ await e2eStopDummyServer(packageJson.name)
+}
diff --git a/e2e/solid-start/basic-head/tests/utils/isPrerender.ts b/e2e/solid-start/basic-head/tests/utils/isPrerender.ts
new file mode 100644
index 0000000000..d5d991d454
--- /dev/null
+++ b/e2e/solid-start/basic-head/tests/utils/isPrerender.ts
@@ -0,0 +1 @@
+export const isPrerender: boolean = process.env.MODE === 'prerender'
diff --git a/e2e/solid-start/basic-head/tests/utils/isPreview.ts b/e2e/solid-start/basic-head/tests/utils/isPreview.ts
new file mode 100644
index 0000000000..7ea362a83e
--- /dev/null
+++ b/e2e/solid-start/basic-head/tests/utils/isPreview.ts
@@ -0,0 +1 @@
+export const isPreview: boolean = process.env.MODE === 'preview'
diff --git a/e2e/solid-start/basic-head/tests/utils/isSpaMode.ts b/e2e/solid-start/basic-head/tests/utils/isSpaMode.ts
new file mode 100644
index 0000000000..b4edb829a8
--- /dev/null
+++ b/e2e/solid-start/basic-head/tests/utils/isSpaMode.ts
@@ -0,0 +1 @@
+export const isSpaMode: boolean = process.env.MODE === 'spa'
diff --git a/e2e/solid-start/basic-head/tsconfig.json b/e2e/solid-start/basic-head/tsconfig.json
new file mode 100644
index 0000000000..d53f9138f5
--- /dev/null
+++ b/e2e/solid-start/basic-head/tsconfig.json
@@ -0,0 +1,24 @@
+{
+ "include": ["**/*.ts", "**/*.tsx", "public/script*.js"],
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "isolatedModules": true,
+ "resolveJsonModule": true,
+ "skipLibCheck": true,
+ "target": "ES2022",
+ "allowJs": true,
+ "forceConsistentCasingInFileNames": true,
+ "baseUrl": ".",
+ "paths": {
+ "~/*": ["./src/*"]
+ },
+ "noEmit": true,
+ "types": ["vite/client"]
+ }
+}
diff --git a/e2e/solid-start/basic-head/vite.config.ts b/e2e/solid-start/basic-head/vite.config.ts
new file mode 100644
index 0000000000..f92f158cb5
--- /dev/null
+++ b/e2e/solid-start/basic-head/vite.config.ts
@@ -0,0 +1,36 @@
+import { defineConfig } from 'vite'
+import tsConfigPaths from 'vite-tsconfig-paths'
+import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
+import viteSolid from 'vite-plugin-solid'
+import { isSpaMode } from './tests/utils/isSpaMode'
+import { isPrerender } from './tests/utils/isPrerender'
+import tailwindcss from '@tailwindcss/vite'
+
+const spaModeConfiguration = {
+ enabled: true,
+ prerender: {
+ outputPath: 'index.html',
+ },
+}
+
+const prerenderConfiguration = {
+ enabled: true,
+ maxRedirects: 100,
+}
+
+export default defineConfig({
+ server: {
+ port: 3000,
+ },
+ plugins: [
+ tailwindcss(),
+ tsConfigPaths({
+ projects: ['./tsconfig.json'],
+ }),
+ tanstackStart({
+ spa: isSpaMode ? spaModeConfiguration : undefined,
+ prerender: isPrerender ? prerenderConfiguration : undefined,
+ }),
+ viteSolid({ ssr: true }),
+ ],
+})
diff --git a/e2e/solid-start/basic-solid-query/package.json b/e2e/solid-start/basic-solid-query/package.json
index 9486fa495b..1552eaaa84 100644
--- a/e2e/solid-start/basic-solid-query/package.json
+++ b/e2e/solid-start/basic-solid-query/package.json
@@ -8,7 +8,7 @@
"dev:e2e": "vite dev",
"build": "vite build && tsc --noEmit",
"preview": "vite preview",
- "start": "pnpx srvx --prod -s ../client dist/server/server.js",
+ "start": "pnpm dlx srvx --prod -s ../client dist/server/server.js",
"test:e2e": "rm -rf port*.txt; playwright test --project=chromium"
},
"dependencies": {
diff --git a/e2e/solid-start/basic-solid-query/src/routeTree.gen.ts b/e2e/solid-start/basic-solid-query/src/routeTree.gen.ts
index c100f876d5..c5d9cf0192 100644
--- a/e2e/solid-start/basic-solid-query/src/routeTree.gen.ts
+++ b/e2e/solid-start/basic-solid-query/src/routeTree.gen.ts
@@ -12,16 +12,19 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as UsersRouteImport } from './routes/users'
import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition'
import { Route as PostsRouteImport } from './routes/posts'
+import { Route as FakeLoginRouteImport } from './routes/fake-login'
import { Route as DeferredRouteImport } from './routes/deferred'
import { Route as LayoutRouteImport } from './routes/_layout'
import { Route as IndexRouteImport } from './routes/index'
import { Route as UsersIndexRouteImport } from './routes/users.index'
import { Route as PostsIndexRouteImport } from './routes/posts.index'
import { Route as UsersUserIdRouteImport } from './routes/users.$userId'
+import { Route as TestHeadDashboardRouteImport } from './routes/test-head/dashboard'
import { Route as PostsPostIdRouteImport } from './routes/posts.$postId'
import { Route as ApiUsersRouteImport } from './routes/api.users'
import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2'
import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query'
+import { Route as TestHeadArticleIdRouteImport } from './routes/test-head/article.$id'
import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep'
import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id'
import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b'
@@ -42,6 +45,11 @@ const PostsRoute = PostsRouteImport.update({
path: '/posts',
getParentRoute: () => rootRouteImport,
} as any)
+const FakeLoginRoute = FakeLoginRouteImport.update({
+ id: '/fake-login',
+ path: '/fake-login',
+ getParentRoute: () => rootRouteImport,
+} as any)
const DeferredRoute = DeferredRouteImport.update({
id: '/deferred',
path: '/deferred',
@@ -71,6 +79,11 @@ const UsersUserIdRoute = UsersUserIdRouteImport.update({
path: '/$userId',
getParentRoute: () => UsersRoute,
} as any)
+const TestHeadDashboardRoute = TestHeadDashboardRouteImport.update({
+ id: '/test-head/dashboard',
+ path: '/test-head/dashboard',
+ getParentRoute: () => rootRouteImport,
+} as any)
const PostsPostIdRoute = PostsPostIdRouteImport.update({
id: '/$postId',
path: '/$postId',
@@ -90,6 +103,11 @@ const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({
path: '/transition/count/query',
getParentRoute: () => rootRouteImport,
} as any)
+const TestHeadArticleIdRoute = TestHeadArticleIdRouteImport.update({
+ id: '/test-head/article/$id',
+ path: '/test-head/article/$id',
+ getParentRoute: () => rootRouteImport,
+} as any)
const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({
id: '/posts_/$postId/deep',
path: '/posts/$postId/deep',
@@ -114,11 +132,13 @@ const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/deferred': typeof DeferredRoute
+ '/fake-login': typeof FakeLoginRoute
'/posts': typeof PostsRouteWithChildren
'/suspense-transition': typeof SuspenseTransitionRoute
'/users': typeof UsersRouteWithChildren
'/api/users': typeof ApiUsersRouteWithChildren
'/posts/$postId': typeof PostsPostIdRoute
+ '/test-head/dashboard': typeof TestHeadDashboardRoute
'/users/$userId': typeof UsersUserIdRoute
'/posts/': typeof PostsIndexRoute
'/users/': typeof UsersIndexRoute
@@ -126,14 +146,17 @@ export interface FileRoutesByFullPath {
'/layout-b': typeof LayoutLayout2LayoutBRoute
'/api/users/$id': typeof ApiUsersIdRoute
'/posts/$postId/deep': typeof PostsPostIdDeepRoute
+ '/test-head/article/$id': typeof TestHeadArticleIdRoute
'/transition/count/query': typeof TransitionCountQueryRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/deferred': typeof DeferredRoute
+ '/fake-login': typeof FakeLoginRoute
'/suspense-transition': typeof SuspenseTransitionRoute
'/api/users': typeof ApiUsersRouteWithChildren
'/posts/$postId': typeof PostsPostIdRoute
+ '/test-head/dashboard': typeof TestHeadDashboardRoute
'/users/$userId': typeof UsersUserIdRoute
'/posts': typeof PostsIndexRoute
'/users': typeof UsersIndexRoute
@@ -141,6 +164,7 @@ export interface FileRoutesByTo {
'/layout-b': typeof LayoutLayout2LayoutBRoute
'/api/users/$id': typeof ApiUsersIdRoute
'/posts/$postId/deep': typeof PostsPostIdDeepRoute
+ '/test-head/article/$id': typeof TestHeadArticleIdRoute
'/transition/count/query': typeof TransitionCountQueryRoute
}
export interface FileRoutesById {
@@ -148,12 +172,14 @@ export interface FileRoutesById {
'/': typeof IndexRoute
'/_layout': typeof LayoutRouteWithChildren
'/deferred': typeof DeferredRoute
+ '/fake-login': typeof FakeLoginRoute
'/posts': typeof PostsRouteWithChildren
'/suspense-transition': typeof SuspenseTransitionRoute
'/users': typeof UsersRouteWithChildren
'/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren
'/api/users': typeof ApiUsersRouteWithChildren
'/posts/$postId': typeof PostsPostIdRoute
+ '/test-head/dashboard': typeof TestHeadDashboardRoute
'/users/$userId': typeof UsersUserIdRoute
'/posts/': typeof PostsIndexRoute
'/users/': typeof UsersIndexRoute
@@ -161,6 +187,7 @@ export interface FileRoutesById {
'/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute
'/api/users/$id': typeof ApiUsersIdRoute
'/posts_/$postId/deep': typeof PostsPostIdDeepRoute
+ '/test-head/article/$id': typeof TestHeadArticleIdRoute
'/transition/count/query': typeof TransitionCountQueryRoute
}
export interface FileRouteTypes {
@@ -168,11 +195,13 @@ export interface FileRouteTypes {
fullPaths:
| '/'
| '/deferred'
+ | '/fake-login'
| '/posts'
| '/suspense-transition'
| '/users'
| '/api/users'
| '/posts/$postId'
+ | '/test-head/dashboard'
| '/users/$userId'
| '/posts/'
| '/users/'
@@ -180,14 +209,17 @@ export interface FileRouteTypes {
| '/layout-b'
| '/api/users/$id'
| '/posts/$postId/deep'
+ | '/test-head/article/$id'
| '/transition/count/query'
fileRoutesByTo: FileRoutesByTo
to:
| '/'
| '/deferred'
+ | '/fake-login'
| '/suspense-transition'
| '/api/users'
| '/posts/$postId'
+ | '/test-head/dashboard'
| '/users/$userId'
| '/posts'
| '/users'
@@ -195,18 +227,21 @@ export interface FileRouteTypes {
| '/layout-b'
| '/api/users/$id'
| '/posts/$postId/deep'
+ | '/test-head/article/$id'
| '/transition/count/query'
id:
| '__root__'
| '/'
| '/_layout'
| '/deferred'
+ | '/fake-login'
| '/posts'
| '/suspense-transition'
| '/users'
| '/_layout/_layout-2'
| '/api/users'
| '/posts/$postId'
+ | '/test-head/dashboard'
| '/users/$userId'
| '/posts/'
| '/users/'
@@ -214,6 +249,7 @@ export interface FileRouteTypes {
| '/_layout/_layout-2/layout-b'
| '/api/users/$id'
| '/posts_/$postId/deep'
+ | '/test-head/article/$id'
| '/transition/count/query'
fileRoutesById: FileRoutesById
}
@@ -221,11 +257,14 @@ export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
LayoutRoute: typeof LayoutRouteWithChildren
DeferredRoute: typeof DeferredRoute
+ FakeLoginRoute: typeof FakeLoginRoute
PostsRoute: typeof PostsRouteWithChildren
SuspenseTransitionRoute: typeof SuspenseTransitionRoute
UsersRoute: typeof UsersRouteWithChildren
ApiUsersRoute: typeof ApiUsersRouteWithChildren
+ TestHeadDashboardRoute: typeof TestHeadDashboardRoute
PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute
+ TestHeadArticleIdRoute: typeof TestHeadArticleIdRoute
TransitionCountQueryRoute: typeof TransitionCountQueryRoute
}
@@ -252,6 +291,13 @@ declare module '@tanstack/solid-router' {
preLoaderRoute: typeof PostsRouteImport
parentRoute: typeof rootRouteImport
}
+ '/fake-login': {
+ id: '/fake-login'
+ path: '/fake-login'
+ fullPath: '/fake-login'
+ preLoaderRoute: typeof FakeLoginRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/deferred': {
id: '/deferred'
path: '/deferred'
@@ -294,6 +340,13 @@ declare module '@tanstack/solid-router' {
preLoaderRoute: typeof UsersUserIdRouteImport
parentRoute: typeof UsersRoute
}
+ '/test-head/dashboard': {
+ id: '/test-head/dashboard'
+ path: '/test-head/dashboard'
+ fullPath: '/test-head/dashboard'
+ preLoaderRoute: typeof TestHeadDashboardRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/posts/$postId': {
id: '/posts/$postId'
path: '/$postId'
@@ -322,6 +375,13 @@ declare module '@tanstack/solid-router' {
preLoaderRoute: typeof TransitionCountQueryRouteImport
parentRoute: typeof rootRouteImport
}
+ '/test-head/article/$id': {
+ id: '/test-head/article/$id'
+ path: '/test-head/article/$id'
+ fullPath: '/test-head/article/$id'
+ preLoaderRoute: typeof TestHeadArticleIdRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/posts_/$postId/deep': {
id: '/posts_/$postId/deep'
path: '/posts/$postId/deep'
@@ -418,11 +478,14 @@ const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
LayoutRoute: LayoutRouteWithChildren,
DeferredRoute: DeferredRoute,
+ FakeLoginRoute: FakeLoginRoute,
PostsRoute: PostsRouteWithChildren,
SuspenseTransitionRoute: SuspenseTransitionRoute,
UsersRoute: UsersRouteWithChildren,
ApiUsersRoute: ApiUsersRouteWithChildren,
+ TestHeadDashboardRoute: TestHeadDashboardRoute,
PostsPostIdDeepRoute: PostsPostIdDeepRoute,
+ TestHeadArticleIdRoute: TestHeadArticleIdRoute,
TransitionCountQueryRoute: TransitionCountQueryRoute,
}
export const routeTree = rootRouteImport
diff --git a/e2e/solid-start/basic-solid-query/src/routes/fake-login.tsx b/e2e/solid-start/basic-solid-query/src/routes/fake-login.tsx
new file mode 100644
index 0000000000..f109df9911
--- /dev/null
+++ b/e2e/solid-start/basic-solid-query/src/routes/fake-login.tsx
@@ -0,0 +1,43 @@
+import { useQueryClient } from '@tanstack/solid-query'
+import { createFileRoute, useNavigate } from '@tanstack/solid-router'
+import { authQy } from '~/utils/fake-auth'
+
+export const Route = createFileRoute('/fake-login')({
+ ssr: false,
+ head: () => ({
+ meta: [{ title: 'Login' }],
+ }),
+ component: LoginPage,
+})
+
+function LoginPage() {
+ const navigate = useNavigate()
+ const queryClient = useQueryClient()
+
+ const handleLogin = () => {
+ localStorage.setItem('auth', 'true')
+
+ // Critical: Invalidate auth query to trigger refetch
+ queryClient.invalidateQueries({ queryKey: authQy.queryKey })
+
+ // Navigate to dashboard, REPLACING login in history
+ navigate({ to: '/test-head/dashboard', replace: true })
+ }
+
+ return (
+
+
+ Login Page
+
+
Click below to simulate login
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-solid-query/src/routes/test-head/article.$id.tsx b/e2e/solid-start/basic-solid-query/src/routes/test-head/article.$id.tsx
new file mode 100644
index 0000000000..4777c073d0
--- /dev/null
+++ b/e2e/solid-start/basic-solid-query/src/routes/test-head/article.$id.tsx
@@ -0,0 +1,86 @@
+import { useQuery } from '@tanstack/solid-query'
+import { createFileRoute, Link } from '@tanstack/solid-router'
+import { Show } from 'solid-js'
+import { authQy, isAuthed } from '~/utils/fake-auth'
+
+// Simulate fetching article - returns null if not authenticated
+const fetchArticle = async (id: string) => {
+ // Simulate API call delay
+ await new Promise((resolve) => setTimeout(resolve, 200))
+
+ const isLoggedIn = isAuthed()
+
+ if (!isLoggedIn) {
+ return null
+ }
+
+ return {
+ title: `Article ${id} Title`,
+ content: `This is the content of article ${id}. Lorem ipsum dolor sit amet, consectetur adipiscing elit.`,
+ }
+}
+
+export const Route = createFileRoute('/test-head/article/$id')({
+ ssr: false,
+ loader: async ({ params }) => {
+ const data = await fetchArticle(params.id)
+ return data
+ },
+
+ head: ({ loaderData }) => {
+ const title = loaderData?.title || 'Article Not Found'
+ console.log('[!] head function: title =', title)
+ return {
+ meta: [{ title }],
+ }
+ },
+
+ component: ArticlePage,
+})
+
+function ArticlePage() {
+ const data = Route.useLoaderData()
+ const authQuery = useQuery(() => authQy)
+
+ return (
+
+ Article not found
+ You need to be authenticated to view this article.
+
+
+ Go to Login โ
+
+
+
+ }
+ >
+
+
+ {data()?.title}
+
+
{data()?.content}
+
+
+
+
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-solid-query/src/routes/test-head/dashboard.tsx b/e2e/solid-start/basic-solid-query/src/routes/test-head/dashboard.tsx
new file mode 100644
index 0000000000..455e54cd08
--- /dev/null
+++ b/e2e/solid-start/basic-solid-query/src/routes/test-head/dashboard.tsx
@@ -0,0 +1,45 @@
+import { createFileRoute } from '@tanstack/solid-router'
+
+export const Route = createFileRoute('/test-head/dashboard')({
+ head: () => ({
+ meta: [{ title: 'Dashboard' }],
+ }),
+ component: DashboardPage,
+})
+
+function DashboardPage() {
+ return (
+
+
+ Dashboard
+
+
+
+
๐งช Now Test the Bug:
+
+ Click your browser's BACK button (or press Alt+โ)
+
+
+
+
What to observe:
+
+ -
+ ๐ Browser tab title - Should update from stale
+ to correct title
+
+ -
+ ๐ Article content - Should load correctly
+
+
+
+
+
โ
WITH NON-BLOCKING FIX:
+
1. Initial head() runs (may show stale title)
+
2. Async loaders complete in background
+
3. All head() functions re-execute (correct title!)
+
+
+
+
+ )
+}
diff --git a/e2e/solid-start/basic-solid-query/src/utils/fake-auth.ts b/e2e/solid-start/basic-solid-query/src/utils/fake-auth.ts
new file mode 100644
index 0000000000..0fae4a1c52
--- /dev/null
+++ b/e2e/solid-start/basic-solid-query/src/utils/fake-auth.ts
@@ -0,0 +1,13 @@
+import { queryOptions } from '@tanstack/solid-query'
+import { createClientOnlyFn } from '@tanstack/solid-start'
+
+export const isAuthed = createClientOnlyFn(
+ () => localStorage.getItem('auth') === 'true',
+)
+
+export const authQy = queryOptions({
+ queryKey: ['auth'],
+ queryFn: isAuthed,
+ staleTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: false,
+})
diff --git a/e2e/solid-start/basic-solid-query/tests/head.spec.ts b/e2e/solid-start/basic-solid-query/tests/head.spec.ts
new file mode 100644
index 0000000000..1790712edb
--- /dev/null
+++ b/e2e/solid-start/basic-solid-query/tests/head.spec.ts
@@ -0,0 +1,99 @@
+import { expect, test } from '@playwright/test'
+
+test.describe('head() function with async loaders and back navigation', () => {
+ test.beforeEach(async ({ page }) => {
+ // Clear auth state before each test
+ await page.goto('/')
+ await page.evaluate(() => localStorage.clear())
+ })
+
+ test('page title updates correctly when navigating back after login', async ({
+ page,
+ }) => {
+ // Step 1: Visit article while unauthenticated
+ await page.goto('/test-head/article/123')
+
+ // Should show "Article Not Found" content and title
+ await expect(page.getByTestId('article-not-found')).toBeVisible()
+ await expect(page).toHaveTitle('Article Not Found')
+
+ // Step 2: Click login link
+ await page.getByTestId('go-to-login-link').click()
+
+ // Should be on login page
+ await expect(page.getByTestId('login-page')).toBeVisible()
+ await expect(page).toHaveTitle('Login')
+
+ // Step 3: Simulate login
+ await page.getByTestId('login-button').click()
+
+ // Should be redirected to dashboard
+ await expect(page.getByTestId('dashboard')).toBeVisible()
+ await expect(page).toHaveTitle('Dashboard')
+
+ // Step 4: Navigate back with browser back button
+ // This is the critical test - the bug was that the title wouldn't update
+ await page.goBack()
+
+ // Wait for the article content to load (proves loader ran)
+ await expect(page.getByTestId('article-content')).toBeVisible()
+ await expect(page.getByTestId('article-title')).toContainText(
+ 'Article 123 Title',
+ )
+
+ // Critical assertion: page title should update to the actual article title
+ // With the bug, this would remain "Article Not Found"
+ // With the fix, head() re-executes after async loaders complete
+ await expect(page).toHaveTitle('Article 123 Title')
+ })
+
+ test('page title shows correct fallback when loader returns null', async ({
+ page,
+ }) => {
+ // Visit article while unauthenticated
+ await page.goto('/test-head/article/456')
+
+ // Should show fallback content and title
+ await expect(page.getByTestId('article-not-found')).toBeVisible()
+ await expect(page).toHaveTitle('Article Not Found')
+ })
+
+ test('logout flow works correctly', async ({ page }) => {
+ // Set up authenticated state
+ await page.goto('/fake-login')
+ await page.getByTestId('login-button').click()
+
+ // Navigate to article
+ await page.goto('/test-head/article/789')
+ await expect(page.getByTestId('article-content')).toBeVisible()
+ await expect(page).toHaveTitle('Article 789 Title')
+
+ // Click logout button
+ await page.getByTestId('logout-button').click()
+
+ // Page should reload and show not found state
+ await expect(page.getByTestId('article-not-found')).toBeVisible()
+ await expect(page).toHaveTitle('Article Not Found')
+ })
+
+ test('rapid navigation does not cause stale head() execution', async ({
+ page,
+ }) => {
+ // Set up authenticated state
+ await page.goto('/fake-login')
+ await page.getByTestId('login-button').click()
+
+ // Navigate to first article
+ await page.goto('/test-head/article/111')
+ await expect(page).toHaveTitle('Article 111 Title')
+
+ // Rapidly navigate to second article
+ await page.goto('/test-head/article/222')
+ await expect(page).toHaveTitle('Article 222 Title')
+
+ // Title should match the current route, not the previous one
+ const title = await page.title()
+ expect(title).toBe('Article 222 Title')
+ expect(title).not.toBe('Article 111 Title')
+ })
+})
diff --git a/e2e/solid-start/basic/src/routeTree.gen.ts b/e2e/solid-start/basic/src/routeTree.gen.ts
index 553ced91ff..4c0a3910b9 100644
--- a/e2e/solid-start/basic/src/routeTree.gen.ts
+++ b/e2e/solid-start/basic/src/routeTree.gen.ts
@@ -40,6 +40,7 @@ import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2'
import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index'
import { Route as TransitionTypingCreateResourceRouteImport } from './routes/transition/typing/create-resource'
import { Route as TransitionCountCreateResourceRouteImport } from './routes/transition/count/create-resource'
+import { Route as TestHeadArticleIdRouteImport } from './routes/test-head/article.$id'
import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader'
import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad'
import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep'
@@ -210,6 +211,11 @@ const TransitionCountCreateResourceRoute =
path: '/transition/count/create-resource',
getParentRoute: () => rootRouteImport,
} as any)
+const TestHeadArticleIdRoute = TestHeadArticleIdRouteImport.update({
+ id: '/test-head/article/$id',
+ path: '/test-head/article/$id',
+ getParentRoute: () => rootRouteImport,
+} as any)
const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({
id: '/via-loader',
path: '/via-loader',
@@ -299,6 +305,7 @@ export interface FileRoutesByFullPath {
'/posts/$postId/deep': typeof PostsPostIdDeepRoute
'/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute
'/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute
+ '/test-head/article/$id': typeof TestHeadArticleIdRoute
'/transition/count/create-resource': typeof TransitionCountCreateResourceRoute
'/transition/typing/create-resource': typeof TransitionTypingCreateResourceRoute
'/redirect/$target/': typeof RedirectTargetIndexRoute
@@ -335,6 +342,7 @@ export interface FileRoutesByTo {
'/posts/$postId/deep': typeof PostsPostIdDeepRoute
'/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute
'/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute
+ '/test-head/article/$id': typeof TestHeadArticleIdRoute
'/transition/count/create-resource': typeof TransitionCountCreateResourceRoute
'/transition/typing/create-resource': typeof TransitionTypingCreateResourceRoute
'/redirect/$target': typeof RedirectTargetIndexRoute
@@ -379,6 +387,7 @@ export interface FileRoutesById {
'/posts_/$postId/deep': typeof PostsPostIdDeepRoute
'/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute
'/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute
+ '/test-head/article/$id': typeof TestHeadArticleIdRoute
'/transition/count/create-resource': typeof TransitionCountCreateResourceRoute
'/transition/typing/create-resource': typeof TransitionTypingCreateResourceRoute
'/redirect/$target/': typeof RedirectTargetIndexRoute
@@ -422,6 +431,7 @@ export interface FileRouteTypes {
| '/posts/$postId/deep'
| '/redirect/$target/via-beforeLoad'
| '/redirect/$target/via-loader'
+ | '/test-head/article/$id'
| '/transition/count/create-resource'
| '/transition/typing/create-resource'
| '/redirect/$target/'
@@ -458,6 +468,7 @@ export interface FileRouteTypes {
| '/posts/$postId/deep'
| '/redirect/$target/via-beforeLoad'
| '/redirect/$target/via-loader'
+ | '/test-head/article/$id'
| '/transition/count/create-resource'
| '/transition/typing/create-resource'
| '/redirect/$target'
@@ -501,6 +512,7 @@ export interface FileRouteTypes {
| '/posts_/$postId/deep'
| '/redirect/$target/via-beforeLoad'
| '/redirect/$target/via-loader'
+ | '/test-head/article/$id'
| '/transition/count/create-resource'
| '/transition/typing/create-resource'
| '/redirect/$target/'
@@ -529,6 +541,7 @@ export interface RootRouteChildren {
MultiCookieRedirectIndexRoute: typeof MultiCookieRedirectIndexRoute
RedirectIndexRoute: typeof RedirectIndexRoute
PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute
+ TestHeadArticleIdRoute: typeof TestHeadArticleIdRoute
TransitionCountCreateResourceRoute: typeof TransitionCountCreateResourceRoute
TransitionTypingCreateResourceRoute: typeof TransitionTypingCreateResourceRoute
}
@@ -752,6 +765,13 @@ declare module '@tanstack/solid-router' {
preLoaderRoute: typeof TransitionCountCreateResourceRouteImport
parentRoute: typeof rootRouteImport
}
+ '/test-head/article/$id': {
+ id: '/test-head/article/$id'
+ path: '/test-head/article/$id'
+ fullPath: '/test-head/article/$id'
+ preLoaderRoute: typeof TestHeadArticleIdRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/redirect/$target/via-loader': {
id: '/redirect/$target/via-loader'
path: '/via-loader'
@@ -963,6 +983,7 @@ const rootRouteChildren: RootRouteChildren = {
MultiCookieRedirectIndexRoute: MultiCookieRedirectIndexRoute,
RedirectIndexRoute: RedirectIndexRoute,
PostsPostIdDeepRoute: PostsPostIdDeepRoute,
+ TestHeadArticleIdRoute: TestHeadArticleIdRoute,
TransitionCountCreateResourceRoute: TransitionCountCreateResourceRoute,
TransitionTypingCreateResourceRoute: TransitionTypingCreateResourceRoute,
}
diff --git a/e2e/solid-start/basic/src/routes/test-head/article.$id.tsx b/e2e/solid-start/basic/src/routes/test-head/article.$id.tsx
new file mode 100644
index 0000000000..95b1c507ee
--- /dev/null
+++ b/e2e/solid-start/basic/src/routes/test-head/article.$id.tsx
@@ -0,0 +1,66 @@
+import { createFileRoute, useRouter } from '@tanstack/solid-router'
+import { Show } from 'solid-js'
+import { fakeLogin, fakeLogout, isAuthed } from '~/utils/fake-auth'
+
+const fetchArticle = async (id: string) => {
+ await new Promise((resolve) => setTimeout(resolve, 1000))
+ return isAuthed()
+ ? {
+ title: `Article Title for ${id}`,
+ content: `Article content for ${id}\n`.repeat(10),
+ }
+ : null
+}
+
+export const Route = createFileRoute('/test-head/article/$id')({
+ ssr: false, // isAuthed is ClientOnly
+ loader: async ({ params }) => {
+ const article = await fetchArticle(params.id)
+ return article
+ },
+ head: ({ loaderData }) => ({
+ meta: [{ title: loaderData?.title ?? 'title n/a' }],
+ }),
+ component: RouteComponent,
+})
+
+function RouteComponent() {
+ const router = useRouter()
+ const data = Route.useLoaderData()
+ return (
+ }>
+ {(article) => (
+
+
{article().content}
+
+
+ )}
+
+ )
+}
+
+function NotAccessible() {
+ const router = useRouter()
+ return (
+
+
Article Not Accessible.
+
+
+ )
+}
diff --git a/e2e/solid-start/basic/src/utils/fake-auth.ts b/e2e/solid-start/basic/src/utils/fake-auth.ts
new file mode 100644
index 0000000000..3c75b3287f
--- /dev/null
+++ b/e2e/solid-start/basic/src/utils/fake-auth.ts
@@ -0,0 +1,16 @@
+import { createClientOnlyFn } from '@tanstack/solid-start'
+
+export { fakeLogin, fakeLogout, isAuthed }
+
+const isAuthed = createClientOnlyFn(() => {
+ const tokenValue = localStorage.getItem('auth')
+ return tokenValue === 'good'
+})
+
+const fakeLogin = createClientOnlyFn(() => {
+ localStorage.setItem('auth', 'good')
+})
+
+const fakeLogout = createClientOnlyFn(() => {
+ localStorage.removeItem('auth')
+})
diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts
index ec72cbfe44..c49f6d7119 100644
--- a/packages/router-core/src/load-matches.ts
+++ b/packages/router-core/src/load-matches.ts
@@ -583,6 +583,27 @@ const executeHead = (
})
}
+const executeAllHeadFns = async (inner: InnerLoadContext) => {
+ // Serially execute head functions for all matches
+ // Each execution is wrapped in try-catch to ensure all heads run even if one fails
+ for (const match of inner.matches) {
+ const { id: matchId, routeId } = match
+ const route = inner.router.looseRoutesById[routeId]!
+ try {
+ const headResult = executeHead(inner, matchId, route)
+ if (headResult) {
+ const head = await headResult
+ inner.updateMatch(matchId, (prev) => ({
+ ...prev,
+ ...head,
+ }))
+ }
+ } catch (err) {
+ console.error(`Error executing head for route ${routeId}:`, err)
+ }
+ }
+}
+
const getLoaderContext = (
inner: InnerLoadContext,
matchId: string,
@@ -815,17 +836,21 @@ const loadRouteMatch = async (
} else if (loaderShouldRunAsync && !inner.sync) {
loaderIsRunningAsync = true
;(async () => {
+ // Capture match reference before try block, because redirect navigation removes it
+ const matchForCleanup = inner.router.getMatch(matchId)!
try {
await runLoader(inner, matchId, index, route)
commitContext()
- const match = inner.router.getMatch(matchId)!
- match._nonReactive.loaderPromise?.resolve()
- match._nonReactive.loadPromise?.resolve()
- match._nonReactive.loaderPromise = undefined
} catch (err) {
if (isRedirect(err)) {
await inner.router.navigate(err.options)
}
+ } finally {
+ // Always resolve promises to allow Promise.allSettled to complete
+ // Use captured reference since navigation might have removed the match
+ matchForCleanup._nonReactive.loaderPromise?.resolve()
+ matchForCleanup._nonReactive.loadPromise?.resolve()
+ matchForCleanup._nonReactive.loaderPromise = undefined
}
})()
} else if (status !== 'success' || (loaderShouldRunAsync && inner.sync)) {
@@ -919,24 +944,33 @@ export async function loadMatches(arg: {
}
}
- // serially execute head functions after all loaders have completed (successfully or not)
- // Each head execution is wrapped in try-catch to ensure all heads run even if one fails
- for (const match of inner.matches) {
- const { id: matchId, routeId } = match
- const route = inner.router.looseRoutesById[routeId]!
- try {
- const headResult = executeHead(inner, matchId, route)
- if (headResult) {
- const head = await headResult
- inner.updateMatch(matchId, (prev) => ({
- ...prev,
- ...head,
- }))
+ // Execute head functions after all loaders have completed (successfully or not)
+ await executeAllHeadFns(inner)
+
+ // Detect if any async loaders are running and schedule re-execution of all head() functions
+ // This ensures head() functions get fresh loaderData after async loaders complete
+ const asyncLoaderPromises = inner.matches
+ .map((match) => {
+ const currentMatch = inner.router.getMatch(match.id)
+ return currentMatch?._nonReactive.loaderPromise
+ })
+ .filter(Boolean)
+
+ if (asyncLoaderPromises.length > 0) {
+ // Schedule re-execution after all async loaders complete (non-blocking)
+ // Use allSettled to handle both successful and failed loaders
+ const rerunPromise: Promise = Promise.allSettled(
+ asyncLoaderPromises,
+ ).then(async () => {
+ // Only execute if this is still the latest scheduled re-run
+ // This handles both:
+ // 1. Navigation to a different location
+ // 2. Route invalidation on the same location (new loader dispatch)
+ if (inner.router.latestHeadRerunPromise === rerunPromise) {
+ await executeAllHeadFns(inner)
}
- } catch (err) {
- // Log error but continue executing other head functions
- console.error(`Error executing head for route ${routeId}:`, err)
- }
+ })
+ inner.router.latestHeadRerunPromise = rerunPromise
}
// Throw notFound after head execution
diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts
index d9d808a318..08f5c08a25 100644
--- a/packages/router-core/src/router.ts
+++ b/packages/router-core/src/router.ts
@@ -894,6 +894,15 @@ export class RouterCore<
viewTransitionPromise?: ControlledPromise
isScrollRestoring = false
isScrollRestorationSetup = false
+ /**
+ * Internal: Tracks the latest scheduled head() re-run promise.
+ * Used to detect when a head re-run has been superseded by a newer one.
+ *
+ * When async loaders complete, we schedule a head re-run. If a new navigation
+ * or invalidation starts before the re-run executes, a new promise is assigned.
+ * The old re-run checks if it's still the latest before executing.
+ */
+ latestHeadRerunPromise?: Promise
// Must build in constructor
__store!: Store>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 48b20d788b..ada871d3eb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3251,6 +3251,58 @@ importers:
specifier: ^4.49.1
version: 4.49.1
+ e2e/solid-start/basic-head:
+ dependencies:
+ '@tanstack/solid-router':
+ specifier: workspace:^
+ version: link:../../../packages/solid-router
+ '@tanstack/solid-router-devtools':
+ specifier: workspace:^
+ version: link:../../../packages/solid-router-devtools
+ '@tanstack/solid-start':
+ specifier: workspace:*
+ version: link:../../../packages/solid-start
+ express:
+ specifier: ^5.1.0
+ version: 5.1.0
+ http-proxy-middleware:
+ specifier: ^3.0.5
+ version: 3.0.5
+ solid-js:
+ specifier: 1.9.10
+ version: 1.9.10
+ vite:
+ specifier: ^7.1.7
+ version: 7.1.7(@types/node@22.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)
+ devDependencies:
+ '@playwright/test':
+ specifier: ^1.56.1
+ version: 1.56.1
+ '@tailwindcss/vite':
+ specifier: ^4.1.18
+ version: 4.1.18(vite@7.1.7(@types/node@22.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))
+ '@tanstack/router-e2e-utils':
+ specifier: workspace:^
+ version: link:../../e2e-utils
+ '@types/node':
+ specifier: 22.10.2
+ version: 22.10.2
+ srvx:
+ specifier: ^0.9.8
+ version: 0.9.8
+ tailwindcss:
+ specifier: ^4.1.18
+ version: 4.1.18
+ typescript:
+ specifier: ^5.7.2
+ version: 5.9.2
+ vite-plugin-solid:
+ specifier: ^2.11.10
+ version: 2.11.10(@testing-library/jest-dom@6.6.3)(solid-js@1.9.10)(vite@7.1.7(@types/node@22.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))
+ vite-tsconfig-paths:
+ specifier: ^5.1.4
+ version: 5.1.4(typescript@5.9.2)(vite@7.1.7(@types/node@22.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))
+
e2e/solid-start/basic-solid-query:
dependencies:
'@tanstack/solid-query':