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

_auth.tsx

28 lines953 Bytes

1import { createFileRoute } from '@tanstack/react-router'
2import * as React from 'react'
3import { redirect } from '@tanstack/react-router'
4import { auth } from '../utils/auth'
5​
6export const Route = createFileRoute('/_auth')({
7 // Before loading, authenticate the user via our auth context
8 // This will also happen during prefetching (e.g. hovering over links, etc)
9 beforeLoad: ({ context, location }) => {
10 // If the user is logged out, redirect them to the login page
11 if (context.auth.status === 'loggedOut') {
12 throw redirect({
13 to: '/login',
14 search: {
15 // Use the current location to power a redirect after login
16 // (Do not use `router.state.resolvedLocation` as it can
17 // potentially lag behind the actual current location)
18 redirect: location.href,
19 },
20 })
21 }
22​
23 // Otherwise, return the user in context
24 return {
25 username: auth.username,
26 }
27 },
28})