When to use Server vs Client in Next.js

From the Next.js cheat sheet · Server & Client Components · verified Jul 2026

When to use Server vs Client

typescript
// USE SERVER COMPONENTS WHEN:
// ✅ Fetching data
// ✅ Accessing backend resources directly
// ✅ Keeping sensitive info on server (API keys, etc)
// ✅ Large dependencies (reduces client bundle)
// ✅ Static content without interactivity

// Server Component Example
async function UserProfile({ userId }: { userId: string }) {
  // Direct database access
  const user = await db.user.findUnique({ where: { id: userId } })
  
  // Access sensitive environment variables
  const apiKey = process.env.SECRET_API_KEY
  
  // Import heavy libraries only on server
  const bcrypt = await import('bcrypt')
  
  return <div>{user.name}</div>
}

// USE CLIENT COMPONENTS WHEN:
// ✅ onClick, onChange, other event handlers
// ✅ useState, useEffect, other React hooks
// ✅ Browser-only APIs (window, document, localStorage)
// ✅ Class components (if needed)
// ✅ Third-party libs that use browser APIs

// Client Component Example
'use client'

function SearchBar() {
  const [query, setQuery] = useState('')
  
  // Need event handler
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    // Search logic
  }
  
  // Need browser API
  useEffect(() => {
    const saved = localStorage.getItem('lastSearch')
    if (saved) setQuery(saved)
  }, [])
  
  return (
    <form onSubmit={handleSearch}>
      <input 
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
    </form>
  )
}
💡 Default to Server Components
⚡ Client for interactivity and browser APIs
📌 Server for data fetching and backend access
🔥 Keep Client Components small and focused

More Next.js tasks

Back to the full Next.js cheat sheet