router: [TanStack Start] HMR is not working from root route (__root)

Describe the bug

HMR is not working in root route. only working from normal routes.

Your Example Website or App

https://github.com/TanStack/router/tree/main/examples/react/start-basic-rsc

Steps to Reproduce the Bug or Issue

  1. Clone (or copy or degit) start-basic-rsc example, install dependencies and run dev server.
  2. Open http://localhost:3000
  3. Try to edit from __root.tsx. I just added a link beside Home.

Expected behavior

In terminal, dev server printed a log about page has reloaded.

[vite] page reload app/routes/__root.tsx

but the changes are not reflected in the browser.

Screenshots or Videos

https://github.com/user-attachments/assets/26aaa1a3-80c1-40af-8dd8-f2403051519e

Platform

  • OS: macOs
  • Browser: Arc / Chrome
  • Version: 126.0.6478.127

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 36
  • Comments: 43 (5 by maintainers)

Most upvoted comments

For anyone reading this who’s looking for a workaround until a fix is merged, you can add the following to your __root.tsx to enable HMR in Tanstack Start:

export const Route = createRootRoute({
  // Other route props like the component
  // ...
  //
  scripts: () =>
    import.meta.env.DEV
      ? [
          {
            type: 'module',
            children: `import RefreshRuntime from "/_build/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type`,
          },
        ]
      : [],
});

This does the same thing as #2286 and #2316 (albeit in a slightly more hacky way). Once the fix is merged, you should be able to safely remove this code from your __root.tsx again

To summarize, we see the following HMR problems with file based routing:

HMR is not triggered when editing

  • routes/__root.tsx
  • components/Example.tsx imported into any routes/**.tsx file
  • routes/_layout.tsx

HMR is triggered when editing

  • routes/index.tsx
  • routes/example.example.tsx (@anulman are you sure this doesn’t work for any plain route (no _ prefix) file?)
  • routes/with-directory/example.tsx

Reproduction

All of this can be testet with the Start Basic StackBlitz. Create a new File app/components/Example.tsx:

export function Example() {
  return <h1>Changing this will not trigger HMR</h1>
}

Now import this into app/routes/index.tsx and render <Example />:

import { createFileRoute } from '@tanstack/react-router'
import { Example } from '~/components/Example'

export const Route = createFileRoute('/')({
  component: Home,
})

function Home() {
  return (
    <div className="p-2">
      <h3>Welcome Home!!!</h3>
      <Example />
    </div>
  )
}

While editing “Welcome Home!!!” will trigger HMR, editing “Changing this will not trigger HMR” will not. The latter shows

[vite] hmr update /app/components/Example.tsx

in the console, but a manual reload is necessary.

This is crazy HMR is not working on any file outside of the routes folder (Tanstack Start) ? Since September ?

I’m experiencing this as well, not just in my root route but in any top-level route.

I also have not been able to separate out components/Foo.tsx files and have them hot-reload. The dev console & JS console confirm the HMR event has been emitted and received, but the React JS—even for route sub-components modified in non-route files (e.g. import { FooPage } from '~/components/FooPage';) does not re-render the HMR’ed component.

The HMR fixes by @lithdew have been merged in and most of the HMR issues should be resolved with the https://github.com/TanStack/router/releases/tag/v1.99.3.

If more, HMR bugs pop up, please open a new Issue on github so that it can be tracked separately.

app/routes/__root.tsx

<head>
...
  {import.meta.env.DEV && (
    <script
      type="module"
      dangerouslySetInnerHTML={{
        __html: `import RefreshRuntime from "/_build/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type`
      }}
    />
  )}
</head>

This work for me

We just added TanStack router to our vite-based project, and now we are also experiencing this HMR failure. I tried a few different routes, it does seem to only be happening with __root.tsx.

Thanks, @MarkSFrancis 's solution works. But the value of scripts should be a regular array, not a function that returns array. Otherwise I get type errors.

Here’s a version that works with "@tanstack/react-router": "^1.95.3" and "@tanstack/start": "^1.95.3":

// __root.tsx

export const Route = createRootRoute({
  // .....
  head: () => ({
    // .....
    scripts: import.meta.env.DEV
      ? [
          {
            type: 'module',
            children: `import RefreshRuntime from "/_build/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type`,
          },
        ]
      : [],
  })
});

I was pulling my hair and wondering why my changes outside of the routes/ but still under app/ are not properly watched. I find it odd that vite’s hrm alludes that it did update when it didn’t. Main reason for the hair pulling. Example of my console:

4:54:13 PM [vite] (client) hmr update /app/components/SideBarMenu.tsx, /app/styles/app.css?direct

My working directory as followed:

app
├── api.tsx
├── client.tsx
├── components
│   ├── SideBarMenu.tsx // -> This does not update ❌
├── routes // -> Anything under routes does update ✅
│   ├── __root.tsx 

My `package.json’ has the following:

    "@tanstack/react-query": "^5.62.10",
    "@tanstack/react-query-devtools": "^5.62.10",
    "@tanstack/react-router": "^1.92.3",
    "@tanstack/react-router-with-query": "^1.92.3",
    "@tanstack/router-devtools": "^1.92.3",
    "@tanstack/router-plugin": "^1.91.1",
    "@tanstack/start": "^1.92.4",

The workaround on this thread that adds a script tag injecting the refresh runtime will throw an error if added to the __root.tsx or anywhere else. The error thrown in the browser is the following:

[plugin:vite-plugin-tanstack-start-create-server-fn] We detected that the '@vitejs/plugin-react' was passed before '@tanstack/start-vite-plugin'. Please make sure that '@tanstack/router-vite-plugin' is passed before '@vitejs/plugin-react' and try again: 
e.g.

plugins: [
  TanStackStartVite(), // Place this before viteReact()
  viteReact(),
]
app/routes/__root.tsx
    at TransformPluginContext.transform (file://node_modules/.pnpm/@tanstack+start-vite-plugin@1.91.1/node_modules/@tanstack/start-vite-plugin/dist/esm/index.js:33:15)
    at EnvironmentPluginContainer.transform (file://node_modules/.pnpm/vite@6.0.6_@types+node@22.10.2_jiti@2.4.2_terser@5.37.0_tsx@4.19.2_yaml@2.6.1/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:47220:19)
    at async loadAndTransform (file://node_modules/.pnpm/vite@6.0.6_@types+node@22.10.2_jiti@2.4.2_terser@5.37.0_tsx@4.19.2_yaml@2.6.1/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:41030:27)
    at async viteTransformMiddleware (file://node_modules/.pnpm/vite@6.0.6_@types+node@22.10.2_jiti@2.4.2_terser@5.37.0_tsx@4.19.2_yaml@2.6.1/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:42474:24
Click outside, press Esc key, or fix the code to dismiss.
You can also disable this overlay by setting server.hmr.overlay to false in vite.config.js.

Any new suggestions will be happy to add to test. For now we keep manually ⌘ + r. Happy holidays

@MarkSFrancis Lifesaver, been trying to work Start into a side project of mine and was pretty sad about the HMR (but its alpha so who cares). A great fix for now until the team gets it going!

@yassine-safraoui I messed it up. It should go inside the return value of the head property’s function. Just updated my comment

okay thanks, I just tried it now and it’s still not working 🫤. I litereally copy pasted the head you have into my root, I made sure i’m exporting the RootComponent, I even tried moving it into its own file(-RootComponent.tsx), the page never hot reloaded when I changed a component inside RouteComponent.

@MarkSFrancis Thanks!

It didn’t work for me at first. I had to marked my Route components for export and now it works!

ie instead of:

export const Route = createFileRoute('/')({
     component: RouteComponent,
   ...
})

function RouteComponent() {
   ...
}

I had to do:

export const Route = createFileRoute('/')({
     component: RouteComponent,
   ...
})

export function RouteComponent() {
   ...
}

@yassine-safraoui I messed it up. It should go inside the return value of the head property’s function. Just updated my comment

@MarkSFrancis Thanks!

It didn’t work for me at first. I had to marked my Route components for export and now it works!

ie instead of:

export const Route = createFileRoute(‘/’)({ component: RouteComponent, … })

function RouteComponent() { … } I had to do:

export const Route = createFileRoute(‘/’)({ component: RouteComponent, … })

export function RouteComponent() { … }

as soon as I used functions instead of const, it worked. You’re god’s send!

I was pulling my hair and wondering why my changes outside of the routes/ but still under app/ are not properly watched. I find it odd that vite’s hrm alludes that it did update when it didn’t. Main reason for the hair pulling. Example of my console:

4:54:13 PM [vite] (client) hmr update /app/components/SideBarMenu.tsx, /app/styles/app.css?direct My working directory as followed:

app ├── api.tsx ├── client.tsx ├── components │ ├── SideBarMenu.tsx // -> This does not update ❌ ├── routes // -> Anything under routes does update ✅ │ ├── __root.tsx My `package.json’ has the following:

"@tanstack/react-query": "^5.62.10",
"@tanstack/react-query-devtools": "^5.62.10",
"@tanstack/react-router": "^1.92.3",
"@tanstack/react-router-with-query": "^1.92.3",
"@tanstack/router-devtools": "^1.92.3",
"@tanstack/router-plugin": "^1.91.1",
"@tanstack/start": "^1.92.4",

The workaround on this thread that adds a script tag injecting the refresh runtime will throw an error if added to the __root.tsx or anywhere else. The error thrown in the browser is the following:

[plugin:vite-plugin-tanstack-start-create-server-fn] We detected that the ‘@vitejs/plugin-react’ was passed before ‘@tanstack/start-vite-plugin’. Please make sure that ‘@tanstack/router-vite-plugin’ is passed before ‘@vitejs/plugin-react’ and try again: e.g.

plugins: [ TanStackStartVite(), // Place this before viteReact() viteReact(), ] app/routes/root.tsx at TransformPluginContext.transform (file://node_modules/.pnpm/@tanstack+start-vite-plugin@1.91.1/node_modules/@tanstack/start-vite-plugin/dist/esm/index.js:33:15) at EnvironmentPluginContainer.transform (file://node_modules/.pnpm/vite@6.0.6@types+node@22.10.2_jiti@2.4.2_terser@5.37.0_tsx@4.19.2_yaml@2.6.1/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:47220:19) at async loadAndTransform (file://node_modules/.pnpm/vite@6.0.6@types+node@22.10.2_jiti@2.4.2_terser@5.37.0_tsx@4.19.2_yaml@2.6.1/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:41030:27) at async viteTransformMiddleware (file://node_modules/.pnpm/vite@6.0.6_@types+node@22.10.2_jiti@2.4.2_terser@5.37.0_tsx@4.19.2_yaml@2.6.1/node_modules/vite/dist/node/chunks/dep-0AosnpPU.js:42474:24 Click outside, press Esc key, or fix the code to dismiss. You can also disable this overlay by setting server.hmr.overlay to false in vite.config.js. Any new suggestions will be happy to add to test. For now we keep manually ⌘ + r. Happy holidays

I’m facing the same issue…

FYI I’m experiencing the same issue (all expect the root routes perform a full reload) when enabling autoCodeSplitting in my tsr.config.json 🫤

{
  "autoCodeSplitting": true
}

@sngmn451 thank you! worked for me too

Currently, while the page is indeed reloaded upon file modification, it does a full page reload instead of a HMR. But this only happens on regular routes, not the __root route (on which HMR works). Using Tanstack Start

Extracting root route component fixed an issue (thanks Claude):

From:

createRootRoute({ component: () => (<></>) }); To:

createRootRoute({ component: RootComponent });

For me this was the issue in all routes! bless you

@MarkSFrancis - worked wonders for me trying to get authentication working, as soon as i added useServerFn everything exploded!! Found this issue and things are rolling again

none of those fixed my issue. I’m not using tanstack start, only tanstack router, but i have the exact same problem