Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import * as React from 'react'
3import { Link, Outlet, redirect, useRouter } from '@tanstack/react-router'
4β
5import { useAuth } from '../auth'
6β
7export const Route = createFileRoute('/_auth')({
8 beforeLoad: ({ context, location }) => {
9 if (!context.auth.isAuthenticated) {
10 throw redirect({
11 to: '/login',
12 search: {
13 redirect: location.href,
14 },
15 })
16 }
17 },
18 component: AuthLayout,
19})
20β
21function AuthLayout() {
22 const router = useRouter()
23 const navigate = Route.useNavigate()
24 const auth = useAuth()
25β
26 const handleLogout = () => {
27 if (window.confirm('Are you sure you want to logout?')) {
28 auth.logout().then(() => {
29 router.invalidate().finally(() => {
30 navigate({ to: '/' })
31 })
32 })
33 }
34 }
35β
36 return (
37 <div className="p-2 h-full">
38 <h1>Authenticated Route</h1>
39 <p>This route's content is only visible to authenticated users.</p>
40 <ul className="py-2 flex gap-2">
41 <li>
42 <Link
43 to="/dashboard"
44 className="hover:underline data-[status='active']:font-semibold"
45 >
46 Dashboard
47 </Link>
48 </li>
49 <li>
50 <Link
51 to="/invoices"
52 className="hover:underline data-[status='active']:font-semibold"
53 >
54 Invoices
55 </Link>
56 </li>
57 <li>
58 <button
59 type="button"
60 className="hover:underline"
61 onClick={handleLogout}
62 >
63 Logout
64 </button>
65 </li>
66 </ul>
67 <hr />
68 <Outlet />
69 </div>
70 )
71}