Back to Home

Next.js Data Fetching Comparison

Three different ways to fetch data in Next.js - Server Component, Client Component, and Server Actions

Server-Side Component

Error

Failed to fetch health status

How it works:

  • • Async Server Component (no 'use client')
  • • Fetches data during page render on server
  • • Uses apiClient directly
  • • Data is pre-rendered as HTML

Client-Side Component

Click the button to check backend health

How it works:

  • • Client Component ('use client')
  • • Fetches data when button is clicked
  • • Uses Next.js API route (/api/health)
  • • Shows loading and error states

Server Action

Click the button to check backend health

How it works:

  • • Client Component with 'use client'
  • • Calls server action (checkHealthAction)
  • • Server action runs on server only
  • • API endpoint hidden from network tab
  • • Uses useTransition for pending state
Loading auth state...

Comparison Table

FeatureServer ComponentClient ComponentServer Action
Where it runsServer onlyBrowser onlyServer only
When it fetchesDuring page renderOn button clickOn button click
API endpoint visible?NoYes (in network tab)No (hidden)
Best forInitial page load, SEOInteractive fetchingMutations, secure operations
Loading stateSuspense boundaryuseStateuseTransition
JavaScript bundleSmallerLargerSmaller
Use caseStatic content, data displayUser interactions, real-timeForm submissions, updates

Key Takeaways

1

Server Components (Blue)

Best for initial page load and SEO. Data is fetched on the server and sent as HTML. No JavaScript needed for rendering.

2

Client Components (Green)

Best for interactive features that need state, effects, or event handlers. Fetches data from the browser using API routes.

3

Server Actions (Purple)

Best for mutations and secure operations. Called from client components but run on the server. API endpoints are completely hidden from users.

Pro Tip: Network Tab Comparison

Open your browser's Network tab and compare the requests:

  • Server Component: No request (data already in HTML)
  • Client Component: Shows GET request to /api/health
  • Server Action: Shows POST request to Next.js internal endpoint (your backend URL is hidden!)