On this page

Secure data fetching and rendering in Next.js

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Server Components​

In the Next.js App Router, all components are Server Components by default. This is a significant paradigm shift from traditional React applications where everything typically runs on the client. Server Components allow you to render React components on the server, bringing numerous benefits.

What are Server Components?​

Fetching Data Directly in Server Components​

One of the most powerful aspects of Server Components is their ability to fetch data directly within the component itself. You can use standard fetch API calls, and Next.js automatically extends fetch to provide advanced caching and revalidation capabilities (which we'll explore more in future modules).

When a Server Component fetches data, this operation happens on the server before the HTML is sent to the client. This means the client receives fully-formed HTML with the data already rendered.

Let's refactor our Task Management App to fetch tasks using a Server Component. To do this, we'll first create a simple mock API endpoint.

Server-Side Rendering (SSR)​

Server-Side Rendering (SSR) refers to the process where a webpage is rendered on the server, and the complete HTML is sent to the client. For Next.js, when a Server Component is dynamically rendered (meaning its content depends on data that changes frequently and needs to be fresh on every request), it exhibits SSR behavior.

In the App Router, a Server Component that uses fetch without specific caching configurations (or with cache: 'no-store') or relies on dynamic functions (like headers() or cookies()) will opt into dynamic rendering, effectively behaving like SSR.

Static Site Generation (SSG)​

Static Site Generation (SSG) is a rendering strategy where pages are pre-rendered at build time. This means the HTML for these pages is generated once when you build your Next.js application, and then served as static files from a CDN (Content Delivery Network).

While our primary task list will be dynamically rendered (SSR-like) due to user-specific data, you might use SSG for pages like an "About TaskFlow" page or a "Features" page.

Loading UI with loading.tsx​

When data is being fetched (especially during SSR), there might be a brief delay before the content is ready to be displayed. Next.js provides a special file convention, loading.tsx (or loading.js), to automatically show a loading state for a route segment while its content is being fetched.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Data fetching and rendering with SSR and SSG

Next

App Integration: Fetching and Displaying Tasks