본문으로 건너뛰기

기본 인증 및 보호된 라우트 설정 방법

이 가이드에서는 TanStack Router 애플리케이션에서 기본 인증 패턴을 구현하고 라우트를 보호하는 방법을 다룹니다.

빠른 시작

컨텍스트를 인식하는 라우터를 만들고 인증 상태 관리를 구현한 다음 라우트 보호에 beforeLoad를 사용해 인증을 설정합니다. 이 가이드에서는 React Context를 사용한 핵심 인증 설정에 중점을 둡니다.


인증 컨텍스트 만들기

src/auth.tsx를 만듭니다.

import React, { createContext, useContext, useState, useEffect } from 'react'

interface User {
id: string
username: string
email: string
}

interface AuthState {
isAuthenticated: boolean
user: User | null
login: (username: string, password: string) => Promise<void>
logout: () => void
}

const AuthContext = createContext<AuthState | undefined>(undefined)

export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null)
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [isLoading, setIsLoading] = useState(true)

// Restore auth state on app load
useEffect(() => {
const token = localStorage.getItem('auth-token')
if (token) {
// Validate token with your API
fetch('/api/validate-token', {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => response.json())
.then((userData) => {
if (userData.valid) {
setUser(userData.user)
setIsAuthenticated(true)
} else {
localStorage.removeItem('auth-token')
}
})
.catch(() => {
localStorage.removeItem('auth-token')
})
.finally(() => {
setIsLoading(false)
})
} else {
setIsLoading(false)
}
}, [])

// Show loading state while checking auth
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
Loading...
</div>
)
}

const login = async (username: string, password: string) => {
// Replace with your authentication logic
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
})

if (response.ok) {
const userData = await response.json()
setUser(userData)
setIsAuthenticated(true)
// Store token for persistence
localStorage.setItem('auth-token', userData.token)
} else {
throw new Error('Authentication failed')
}
}

const logout = () => {
setUser(null)
setIsAuthenticated(false)
localStorage.removeItem('auth-token')
}

return (
<AuthContext.Provider value={{ isAuthenticated, user, login, logout }}>
{children}
</AuthContext.Provider>
)
}

export function useAuth() {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}

라우터 컨텍스트 구성

1. 라우터 컨텍스트 설정

src/routes/__root.tsx를 업데이트합니다.

import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'

interface AuthState {
isAuthenticated: boolean
user: { id: string; username: string; email: string } | null
login: (username: string, password: string) => Promise<void>
logout: () => void
}

interface MyRouterContext {
auth: AuthState
}

export const Route = createRootRouteWithContext<MyRouterContext>()({
component: () => (
<div>
<Outlet />
<TanStackRouterDevtools />
</div>
),
})

2. 라우터 구성

src/router.tsx를 업데이트합니다.

import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

export const router = createRouter({
routeTree,
context: {
// auth will be passed down from App component
auth: undefined!,
},
})

declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}

3. 앱을 인증과 연결

src/App.tsx를 업데이트합니다.

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>
)
}

export default App

보호된 라우트 만들기

1. 인증 레이아웃 라우트 만들기

src/routes/_authenticated.tsx를 만듭니다.

import { createFileRoute, redirect, Outlet } from '@tanstack/react-router'

export const Route = createFileRoute('/_authenticated')({
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
throw redirect({
to: '/login',
search: {
// Save current location for redirect after login
redirect: location.href,
},
})
}
},
component: () => <Outlet />,
})

2. 로그인 라우트 만들기

src/routes/login.tsx를 만듭니다.

import { createFileRoute, redirect } from '@tanstack/react-router'
import { useState } from 'react'

export const Route = createFileRoute('/login')({
validateSearch: (search) => ({
redirect: (search.redirect as string) || '/',
}),
beforeLoad: ({ context, search }) => {
// Redirect if already authenticated
if (context.auth.isAuthenticated) {
throw redirect({ to: search.redirect })
}
},
component: LoginComponent,
})

function LoginComponent() {
const { auth } = Route.useRouteContext()
const { redirect } = Route.useSearch()
const navigate = Route.useNavigate()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState('')

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
setError('')

try {
await auth.login(username, password)
// Navigate to the redirect URL using router navigation
navigate({ to: redirect })
} catch (err) {
setError('Invalid username or password')
} finally {
setIsLoading(false)
}
}

return (
<div className="min-h-screen flex items-center justify-center">
<form
onSubmit={handleSubmit}
className="max-w-md w-full space-y-4 p-6 border rounded-lg"
>
<h1 className="text-2xl font-bold text-center">Sign In</h1>

{error && (
<div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
{error}
</div>
)}

<div>
<label htmlFor="username" className="block text-sm font-medium mb-1">
Username
</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>

<div>
<label htmlFor="password" className="block text-sm font-medium mb-1">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>

<button
type="submit"
disabled={isLoading}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Signing in...' : 'Sign In'}
</button>
</form>
</div>
)
}

3. 보호된 대시보드 만들기

src/routes/_authenticated/dashboard.tsx를 만듭니다.

import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/_authenticated/dashboard')({
component: DashboardComponent,
})

function DashboardComponent() {
const { auth } = Route.useRouteContext()

return (
<div className="p-6">
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold">Dashboard</h1>
<button
onClick={auth.logout}
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700"
>
Sign Out
</button>
</div>

<div className="bg-white p-6 rounded-lg shadow">
<h2 className="text-xl font-semibold mb-2">Welcome back!</h2>
<p className="text-gray-600">
Hello, <strong>{auth.user?.username}</strong>! You are successfully
authenticated.
</p>
<p className="text-sm text-gray-500 mt-2">Email: {auth.user?.email}</p>
</div>
</div>
)
}

인증 지속성 추가

페이지를 새로 고칠 때 인증 상태를 복원하도록 AuthProvider를 업데이트합니다.

export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null)
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [isLoading, setIsLoading] = useState(true)

// Restore auth state on app load
useEffect(() => {
const token = localStorage.getItem('auth-token')
if (token) {
// Validate token with your API
fetch('/api/validate-token', {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => response.json())
.then((userData) => {
if (userData.valid) {
setUser(userData.user)
setIsAuthenticated(true)
} else {
localStorage.removeItem('auth-token')
}
})
.catch(() => {
localStorage.removeItem('auth-token')
})
.finally(() => {
setIsLoading(false)
})
} else {
setIsLoading(false)
}
}, [])

// Show loading state while checking auth
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
Loading...
</div>
)
}

// ... rest of the provider logic
}

프로덕션 체크리스트

인증을 배포하기 전에 다음 항목을 확인합니다.

  • 적절한 인증 미들웨어로 API 엔드포인트를 보호했는지 확인합니다.
  • 프로덕션에서 HTTPS를 설정했는지 확인합니다(보안 쿠키에 필요함).
  • API 엔드포인트의 환경 변수를 구성했는지 확인합니다.
  • 적절한 토큰 검증 및 갱신을 구현했는지 확인합니다.
  • 폼 기반 인증에 CSRF 보호를 추가했는지 확인합니다.
  • 인증 흐름(로그인, 로그아웃, 지속성)을 테스트했는지 확인합니다.
  • 네트워크 오류에 대한 적절한 오류 처리를 추가했는지 확인합니다.
  • 인증 작업의 로딩 상태를 구현했는지 확인합니다.

일반적인 문제

인증 컨텍스트를 사용할 수 없음

문제: useAuth must be used within an AuthProvider 오류가 발생합니다.

해결 방법: AuthProvider가 앱 전체를 감싸고 그 안에 RouterProvider가 있는지 확인합니다.

페이지를 새로 고치면 로그아웃됨

문제: 페이지를 새로 고치면 인증 상태가 초기화됩니다.

해결 방법: 위의 지속성 섹션에 설명된 대로 토큰 지속성을 추가합니다.

리디렉션 전에 보호된 라우트가 잠시 표시됨

문제: 로그인으로 리디렉션되기 전에 보호된 콘텐츠가 잠시 표시됩니다.

해결 방법: 컴포넌트 수준의 인증 검사 대신 beforeLoad를 사용합니다.

export const Route = createFileRoute('/_authenticated/dashboard')({
beforeLoad: ({ context }) => {
if (!context.auth.isAuthenticated) {
throw redirect({ to: '/login' })
}
},
component: DashboardComponent,
})

일반적인 다음 단계

기본 인증을 설정한 후 다음 작업을 수행할 수 있습니다.