Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions docs/start/framework/react/client-entry-point.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,46 @@ hydrateRoot(
)
```

## Custom `useId` prefix
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seems to be the wrong file for this, as it affects not only the client entrypoint but also getRouter


You can customize the prefix of react's `useId` hook.

```tsx
// src/client.tsx
import { StartClient } from '@tanstack/react-start/client'
import { StrictMode } from 'react'
import { hydrateRoot } from 'react-dom/client'
import { ErrorBoundary } from './components/ErrorBoundary'

hydrateRoot(
document,
<StrictMode>
<ErrorBoundary>
<StartClient />
</ErrorBoundary>
</StrictMode>,
{
identifierPrefix: 'custom-prefix', // ⚠️ These values must be the identical to prevent hydration errors!
},
)
```

```tsx
// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

export function getRouter() {
const router = createRouter({
routeTree,
scrollRestoration: true,
ssr: {
identifierPrefix: 'custom-prefix', // ⚠️ These values must be the identical to prevent hydration errors!
},
})

return router
}
```

The client entry point gives you full control over how your application initializes on the client side while working seamlessly with TanStack Start's server-side rendering.
20 changes: 20 additions & 0 deletions e2e/react-start/custom-identifier-prefix/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
node_modules
package-lock.json
yarn.lock

.DS_Store
.cache
.env
.vercel
.output

/build/
/api/
/server/build
/public/build
# Sentry Config File
.env.sentry-build-plugin
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
4 changes: 4 additions & 0 deletions e2e/react-start/custom-identifier-prefix/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**/build
**/public
pnpm-lock.yaml
routeTree.gen.ts
45 changes: 45 additions & 0 deletions e2e/react-start/custom-identifier-prefix/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "tanstack-react-start-e2e-custom-identifier-prefix",
"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",
"start": "pnpx srvx --prod -s ../client dist/server/server.js",
"start:spa": "node server.js",
"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": "pnpm run test:e2e:spaMode && pnpm run test:e2e:ssrMode"
},
"dependencies": {
"@tanstack/react-router": "workspace:^",
"@tanstack/react-router-devtools": "workspace:^",
"@tanstack/react-start": "workspace:^",
"express": "^5.1.0",
"http-proxy-middleware": "^3.0.5",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"redaxios": "^0.5.1",
"tailwind-merge": "^2.6.0"
},
"devDependencies": {
"@playwright/test": "^1.50.1",
"@tanstack/router-e2e-utils": "workspace:^",
"@types/node": "^22.10.2",
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.3",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"combinate": "^1.1.11",
"postcss": "^8.5.1",
"srvx": "^0.8.6",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.2",
"vite": "^7.1.7",
"vite-tsconfig-paths": "^5.1.4",
"zod": "^3.24.2"
}
}
60 changes: 60 additions & 0 deletions e2e/react-start/custom-identifier-prefix/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { defineConfig, devices } from '@playwright/test'
import {
getDummyServerPort,
getTestServerPort,
} from '@tanstack/router-e2e-utils'
import { isSpaMode } from './tests/utils/isSpaMode'
import packageJson from './package.json' with { type: 'json' }

const PORT = await getTestServerPort(
`${packageJson.name}${isSpaMode ? '_spa' : ''}`,
)
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`

console.log('running in spa mode: ', isSpaMode.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: isSpaMode ? spaModeCommand : ssrModeCommand,
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'],
},
},
],
})
6 changes: 6 additions & 0 deletions e2e/react-start/custom-identifier-prefix/postcss.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions e2e/react-start/custom-identifier-prefix/public/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
console.log('SCRIPT_1 loaded')
window.SCRIPT_1 = true
2 changes: 2 additions & 0 deletions e2e/react-start/custom-identifier-prefix/public/script2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
console.log('SCRIPT_2 loaded')
window.SCRIPT_2 = true
19 changes: 19 additions & 0 deletions e2e/react-start/custom-identifier-prefix/public/site.webmanifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "",
"short_name": "",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
67 changes: 67 additions & 0 deletions e2e/react-start/custom-identifier-prefix/server.js
Original file line number Diff line number Diff line change
@@ -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}`)
}),
)
19 changes: 19 additions & 0 deletions e2e/react-start/custom-identifier-prefix/src/client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// DO NOT DELETE THIS FILE!!!
// This file is a good smoke test to make sure the custom client entry is working
import { StrictMode, startTransition } from 'react'
import { hydrateRoot } from 'react-dom/client'
import { StartClient } from '@tanstack/react-start/client'

console.log("[client-entry]: using custom client entry in 'src/client.tsx'")

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<StartClient />
</StrictMode>,
{
identifierPrefix: 'myapp',
},
)
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
ErrorComponent,
Link,
rootRouteId,
useMatch,
useRouter,
} from '@tanstack/react-router'
import type { ErrorComponentProps } from '@tanstack/react-router'

export function DefaultCatchBoundary({ error }: ErrorComponentProps) {
const router = useRouter()
const isRoot = useMatch({
strict: false,
select: (state) => state.id === rootRouteId,
})

console.error(error)

return (
<div className="min-w-0 flex-1 p-4 flex flex-col items-center justify-center gap-6">
<ErrorComponent error={error} />
<div className="flex gap-2 items-center flex-wrap">
<button
onClick={() => {
router.invalidate()
}}
className={`px-2 py-1 bg-gray-600 dark:bg-gray-700 rounded text-white uppercase font-extrabold`}
>
Try Again
</button>
{isRoot ? (
<Link
to="/"
className={`px-2 py-1 bg-gray-600 dark:bg-gray-700 rounded text-white uppercase font-extrabold`}
>
Home
</Link>
) : (
<Link
to="/"
className={`px-2 py-1 bg-gray-600 dark:bg-gray-700 rounded text-white uppercase font-extrabold`}
onClick={(e) => {
e.preventDefault()
window.history.back()
}}
>
Go Back
</Link>
)}
</div>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Link } from '@tanstack/react-router'

export function NotFound({ children }: { children?: any }) {
return (
<div className="space-y-2 p-2" data-testid="default-not-found-component">
<div className="text-gray-600 dark:text-gray-400">
{children || <p>The page you are looking for does not exist.</p>}
</div>
<p className="flex items-center gap-2 flex-wrap">
<button
onClick={() => window.history.back()}
className="bg-emerald-500 text-white px-2 py-1 rounded uppercase font-black text-sm"
>
Go back
</button>
<Link
to="/"
className="bg-cyan-600 text-white px-2 py-1 rounded uppercase font-black text-sm"
>
Start Over
</Link>
</p>
</div>
)
}
Loading
Loading