Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

__root.tsx

117 lines2.8 KB

1/// <reference types="vite/client" />
2import type { ReactNode } from 'react'
3import type { AuthSession } from 'start-authjs'
4import {
5 HeadContent,
6 Link,
7 Outlet,
8 Scripts,
9 createRootRouteWithContext,
10} from '@tanstack/react-router'
11import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
12import { createServerFn } from '@tanstack/react-start'
13import { getRequest } from '@tanstack/react-start/server'
14import { getSession } from 'start-authjs'
15import { authConfig } from '~/utils/auth'
16import appCss from '~/styles/app.css?url'
17​
18interface RouterContext {
19 session: AuthSession | null
21​
22const fetchSession = createServerFn({ method: 'GET' }).handler(async () => {
23 const request = getRequest()
24 const session = await getSession(request, authConfig)
25 return session
26})
27​
28export const Route = createRootRouteWithContext<RouterContext>()({
29 beforeLoad: async () => {
30 const session = await fetchSession()
31 return {
32 session,
33 }
34 },
35 head: () => ({
36 meta: [
37 {
38 charSet: 'utf-8',
39 },
40 {
41 name: 'viewport',
42 content: 'width=device-width, initial-scale=1',
43 },
44 {
45 title: 'TanStack Start Auth Example',
46 },
47 ],
48 links: [{ rel: 'stylesheet', href: appCss }],
49 }),
50 component: RootComponent,
51})
52​
53function RootComponent() {
54 return (
55 <RootDocument>
56 <Outlet />
57 </RootDocument>
58 )
60​
61function RootDocument({ children }: { children: ReactNode }) {
62 return (
63 <html>
64 <head>
65 <HeadContent />
66 </head>
67 <body>
68 <NavBar />
69 <main className="p-4">{children}</main>
70 <TanStackRouterDevtools position="bottom-right" />
71 <Scripts />
72 </body>
73 </html>
74 )
76​
77function NavBar() {
78 const routeContext = Route.useRouteContext()
79​
80 return (
81 <nav className="p-4 flex gap-4 items-center bg-gray-100">
82 <Link
83 to="/"
84 activeProps={{ className: 'font-bold' }}
85 activeOptions={{ exact: true }}
86 >
87 Home
88 </Link>
89 <Link to="/protected" activeProps={{ className: 'font-bold' }}>
90 Protected
91 </Link>
92 <div className="ml-auto flex items-center gap-4">
93 {routeContext.session ? (
94 <>
95 <span className="text-gray-600">
96 {routeContext.session?.user?.name ||
97 routeContext.session?.user?.email}
98 </span>
99 <a
100 href="/api/auth/signout"
101 className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
102 >
103 Sign Out
104 </a>
105 </>
106 ) : (
107 <Link
108 to="/login"
109 className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
110 >
111 Sign In
112 </Link>
113 )}
114 </div>
115 </nav>
116 )