Authentication System
Build a complete auth system with login, signup, and protected routes
What you'll learn
Implement sign-up and sign-in with email and password
Protect routes with authentication middleware
Manage session state with JWT tokens or cookies
Handle token refresh and automatic re-authentication
Build protected API routes that verify user identity
Implement logout and token invalidation
Build a full authentication system.
Requirements
- User registration with email + password
- Login with session management
- Protected routes that redirect to login
- Password reset flow
- Profile page with user info
Starter
// Auth context
"use client"
import { createContext, useContext, useState } from "react"
interface AuthUser {
id: string
email: string
name: string
}
const AuthContext = createContext<{
user: AuthUser | null
login: (email: string, password: string) => Promise<void>
logout: () => void
signup: (email: string, password: string, name: string) => Promise<void>
} | null>(null)
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(null)
// TODO: implement login, signup, logout
return (
<AuthContext.Provider value={{ user, login, logout, signup }}>
{children}
</AuthContext.Provider>
)
}
export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error("useAuth must be inside AuthProvider")
return ctx
}
Next Steps
Key Takeaways
User authentication requires both sign-up (registration) and sign-in (login) endpoints
Route protection is typically implemented as a higher-order component or middleware that checks auth state
JWT tokens contain encoded user information and are verified server-side with a secret key
Token refresh cycles prevent short-lived tokens from forcing frequent re-logins
Protected API routes verify the token before processing the request, rejecting unauthenticated calls with 401