认证是 Web 应用程序极其常见的需求。在本指南中,我们将介绍如何使用 TanStack Router 构建受保护的路由,以及如何在用户尝试访问它们时将用户重定向到登录页面。
route.beforeLoad 选项允许您指定一个在路由加载之前调用的函数。它接收与 route.loader 函数相同的所有参数。这是检查用户是否已认证的好地方,如果没有认证则将他们重定向到登录页面。
beforeLoad 函数相对于这些其他路由加载函数按以下顺序运行:
重要的是要知道路由的 beforeLoad 函数在其任何子路由的 beforeLoad 函数之前被调用。 它本质上是路由及其所有子路由的中间件函数。
如果您在 beforeLoad 中抛出错误,其子路由都不会尝试加载。
虽然不是必需的,但某些认证流程需要重定向到登录页面。为此,您可以从 beforeLoad 抛出 redirect():
// src/routes/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
beforeLoad: async ({ location }) => {
if (!isAuthenticated()) {
throw redirect({
to: '/login',
search: {
// Use the current location to power a redirect after login
// (Do not use `router.state.resolvedLocation` as it can
// potentially lag behind the actual current location)
redirect: location.href,
},
})
}
},
})
// src/routes/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
beforeLoad: async ({ location }) => {
if (!isAuthenticated()) {
throw redirect({
to: '/login',
search: {
// Use the current location to power a redirect after login
// (Do not use `router.state.resolvedLocation` as it can
// potentially lag behind the actual current location)
redirect: location.href,
},
})
}
},
})
Tip
redirect() 函数接受与 navigate 函数相同的所有选项,因此如果您想替换当前历史记录条目而不是添加新条目,可以传递 replace: true 等选项。
一旦您认证了用户,通常的做法是将他们重定向回他们试图访问的页面。为此,您可以利用我们在原始重定向中添加的 redirect 搜索参数。由于我们将用原来的 URL 替换整个 URL,router.history.push 比 router.navigate 更适合这种情况:
router.history.push(search.redirect)
router.history.push(search.redirect)
一些应用程序选择不将用户重定向到登录页面,而是让用户留在同一页面上,并显示一个登录表单,该表单要么替换主要内容,要么通过模态框隐藏它。这在 TanStack Router 中也是可能的,只需简单地短路渲染通常会渲染子路由的 <Outlet />:
// src/routes/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
component: () => {
if (!isAuthenticated()) {
return <Login />
}
return <Outlet />
},
})
// src/routes/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
component: () => {
if (!isAuthenticated()) {
return <Login />
}
return <Outlet />
},
})
这使用户保持在同一页面上,但仍然允许您渲染登录表单。一旦用户通过认证,您可以简单地渲染 <Outlet />,子路由就会被渲染。
如果您的认证流程依赖于与 React context 和/或 hooks 的交互,您需要使用 router.context 选项将认证状态传递给 TanStack Router。
Important
React hooks 不应该在 React 组件之外使用。如果您需要在 React 组件之外使用 hook,您需要在包装 <RouterProvider /> 的组件中从 hook 提取返回的状态,然后将返回的值传递给 TanStack Router。
我们将在 Router Context 部分详细介绍 router.context 选项。
以下是一个在 TanStack Router 中使用 React context 和 hooks 保护认证路由的示例。请参阅 Authenticated Routes 示例 中的完整工作设置。
import { createRootRouteWithContext } from '@tanstack/react-router'
interface MyRouterContext {
// The ReturnType of your useAuth hook or the value of your AuthContext
auth: AuthState
}
export const Route = createRootRouteWithContext<MyRouterContext>()({
component: () => <Outlet />,
})
import { createRootRouteWithContext } from '@tanstack/react-router'
interface MyRouterContext {
// The ReturnType of your useAuth hook or the value of your AuthContext
auth: AuthState
}
export const Route = createRootRouteWithContext<MyRouterContext>()({
component: () => <Outlet />,
})
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
export const router = createRouter({
routeTree,
context: {
// auth will initially be undefined
// We'll be passing down the auth state from within a React component
auth: undefined!,
},
})
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
export const router = createRouter({
routeTree,
context: {
// auth will initially be undefined
// We'll be passing down the auth state from within a React component
auth: undefined!,
},
})
import { RouterProvider } from '@tanstack/react-router'
import { AuthProvider, useAuth } from './auth'
import { router } from './router'
function InnerApp() {
const auth = useAuth()
return <RouterProvider router={router} context={{ auth }} />
}
function App() {
return (
<AuthProvider>
<InnerApp />
</AuthProvider>
)
}
import { RouterProvider } from '@tanstack/react-router'
import { AuthProvider, useAuth } from './auth'
import { router } from './router'
function InnerApp() {
const auth = useAuth()
return <RouterProvider router={router} context={{ auth }} />
}
function App() {
return (
<AuthProvider>
<InnerApp />
</AuthProvider>
)
}
然后在认证路由中,您可以使用 beforeLoad 函数检查认证状态,如果用户未登录,则抛出 redirect() 到您的登录路由。
import { createFileRoute, redirect } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard')({
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
},
})
import { createFileRoute, redirect } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard')({
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
},
})
您也可以_可选地_使用非重定向认证方法来显示登录表单,而不是调用重定向。
这种方法也可以与无路径或布局路由结合使用,以保护其父路由下的所有路由。