Menu

Fetching Data in Server Components

Lesson 1: Fetching Data in Server Components

How do you fetch data on the server?

Make the component async and await the data. There is no useEffect, no loading state variable, and no API layer in between.

Source How to fetch
External REST API await fetch(url)
Database ORM or query client, e.g. await db.course.findMany()
Local files await readFile(path) from node:fs/promises
CMS or SDK The provider's SDK, e.g. await cms.getEntries()

Example

// app/courses/page.tsx
type Course = { id: string; slug: string; title: string; level: string };

async function getCourses(): Promise<Course[]> {
  const res = await fetch('https://api.learnhub.in/courses');
  if (!res.ok) throw new Error(`Failed to load courses: ${res.status}`);
  return res.json();
}

export default async function CoursesPage() {
  const courses = await getCourses();

  if (courses.length === 0) {
    return <p>No courses yet. Check back soon.</p>;
  }

  return (
    <ul>
      {courses.map((c) => (
        <li key={c.id}>{c.title} – {c.level}</li>
      ))}
    </ul>
  );
}

How it works

  1. Next.js runs the page on the server and waits for getCourses().
  2. If the response is not OK, the thrown error is caught by the nearest error.tsx.
  3. The rendered list is sent as HTML. The API URL and any keys stay on the server.

Caching defaults (Next.js 15 and later):

Behaviour Default
fetch responses cached between requests No
Identical fetch calls within one render deduplicated Yes (request memoisation)
Route prerendered at build if it uses no request data Yes, unless Cache Components is enabled

You opt in to caching explicitly. Module 7 covers 'use cache', cacheLife, and revalidation.

Common mistakes

Mistake Effect Fix
Not checking res.ok Error pages show "undefined" instead of failing clearly Throw on non-OK responses
Fetching in useEffect by habit Slower load, extra client code Fetch in the Server Component
Calling fetch('/api/courses') from a Server Component Fails (no base URL) and adds a hop Call the data function directly
No empty state Blank page confuses users Handle length === 0

Key takeaways

  • Fetch in async Server Components by default.
  • Handle errors and empty states explicitly.
  • Data is not cached unless you ask for it.

Try it: Fetch courses from a public JSON API (or a local file) and render them with an empty state and an error.tsx fallback.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details