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

__root.tsx

121 lines2.9 KB

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