Skip to main content

Next.js Data Fetching Explained: CSR, SSR, SSG, ISR with Axios & WebSockets

Understanding Data Fetching in Next.js: CSR, SSR, SSG, and ISR with Axios & WebSockets

Next.js provides multiple ways to fetch data from an API: CSR (Client-Side Rendering), SSR (Server-Side Rendering), SSG (Static Site Generation), and ISR (Incremental Static Regeneration).

Each method serves a different purpose, affecting performance, SEO, and user experience. In this guide, we will explore how to use Axios for API requests and integrate WebSockets for real-time updates.

🔹 1. CSR (Client-Side Rendering) - Fetch Data with Axios

CSR means fetching data on the client side, after the component mounts. The data is NOT available during the initial page load.

✅ When to Use CSR?

  • For real-time updates (e.g., chat apps, stock prices).
  • When SEO is not a priority (search engines see an empty page first).
  • For highly interactive applications.

📌 Example: Fetching Data with Axios in CSR


import { useEffect, useState } from 'react';
import axios from 'axios';

export default function CSRPage() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then((response) => {
        setData(response.data);
        setLoading(false);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;

  return (
    <div>
      <h1>Client-Side Rendered Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
---

🔹 2. CSR with WebSockets - Real-Time Updates

WebSockets allow two-way communication between the client and the server. They are useful for real-time updates in chat apps, notifications, or stock market data.

📌 Example: Adding WebSockets for Live Data Updates


import { useEffect, useState } from 'react';

export default function WebSocketComponent() {
  const [message, setMessage] = useState('Waiting for updates...');

  useEffect(() => {
    const socket = new WebSocket('wss://api.example.com/realtime');

    socket.onmessage = (event) => {
      setMessage(event.data);
    };

    return () => socket.close();
  }, []);

  return (
    <div>
      <h1>WebSocket Live Updates</h1>
      <p>{message}</p>
    </div>
  );
}
---

🔹 3. SSR (Server-Side Rendering) - Fetch Data on Every Request

SSR fetches data on the server before sending the page to the client. This ensures fresh data for every request.

✅ When to Use SSR?

  • When SEO is important (data is available to search engines).
  • For user-specific content (e.g., dashboards).
  • If you need real-time data on every request.

📌 Example: Fetching Data with Axios in SSR


import axios from 'axios';

export default function SSRPage({ data }) {
  return (
    <div>
      <h1>Server-Side Rendered Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export async function getServerSideProps() {
  try {
    const res = await axios.get('https://api.example.com/data');
    return { props: { data: res.data } };
  } catch (error) {
    console.error('Error fetching data:', error);
    return { props: { data: null } };
  }
}
---

🔹 4. SSG (Static Site Generation) - Pre-Generated Pages

SSG fetches data at build time and generates static HTML pages. This method is fast but not useful for frequently changing data.

✅ When to Use SSG?

  • For blogs, documentation, and marketing pages.
  • When data doesn't change often.

📌 Example: Fetching Data with Axios in SSG


import axios from 'axios';

export default function SSGPage({ data }) {
  return (
    <div>
      <h1>Static Site Generated Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export async function getStaticProps() {
  try {
    const res = await axios.get('https://api.example.com/data');
    return { props: { data: res.data } };
  } catch (error) {
    console.error('Error fetching data:', error);
    return { props: { data: null } };
  }
}
---

🔹 5. ISR (Incremental Static Regeneration) - Automatic Updates

ISR allows static pages to be regenerated after a set interval. It combines the benefits of **SSG** and **SSR**.

✅ When to Use ISR?

  • For news, product listings, and price updates.
  • When you need a balance between speed and fresh data.

📌 Example: Fetching Data with Axios in ISR


import axios from 'axios';

export default function ISRPage({ data }) {
  return (
    <div>
      <h1>Incrementally Static Regenerated Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export async function getStaticProps() {
  try {
    const res = await axios.get('https://api.example.com/data');
    return {
      props: { data: res.data },
      revalidate: 60, // Regenerate every 60 seconds
    };
  } catch (error) {
    console.error('Error fetching data:', error);
    return { props: { data: null } };
  }
}
---

📌 Conclusion

Method Best For SEO Fresh Data
CSR Real-time updates No Yes
SSR Dashboards, user data Yes Yes
SSG Blogs, marketing Yes No
ISR News, product pages Yes Partial

Choose the right method based on your needs! 🚀

Comments

Popular posts from this blog

How to Convert a Next.js Website into a PWA and TWA

🚀 Complete Guide: Converting Next.js to PWA & TWA Transform your Next.js website into a Progressive Web App and wrap it as an Android application using Trusted Web Activity. Every step explained in detail! 📋 Table of Contents What is a PWA? What is a TWA? Prerequisites & Setup Step 1: Convert Next.js to PWA Install Dependencies Configure next.config.js Create Web App Manifest Prepare App Icons Update Document Head Build and Test PWA Step 2: Wrap PWA as TWA Create Asset Links File Install Bubblewrap CLI ...

DevOps Best Practices

 # DevOps Best Practices: Your Ultimate Guide to Modern Software Development In today's fast-paced tech world, DevOps isn't just a buzzword – it's a game-changer. Let's dive into the essential practices that can transform your software development process. ![DevOps Lifecycle](https://blogger.googleusercontent.com/img/placeholder.png) ## 🔄 1. Continuous Integration (CI) - The Foundation Think of CI as your code's quality guardian. Every time developers push code, automated tests run to catch issues early. Here's what makes great CI: - Automated builds triggered with every commit - Comprehensive test suites running automatically - Code quality checks integrated into the pipeline - Quick feedback loops to developers **Pro Tip:** Start with simple automated tests and gradually build up your test suite. Remember, it's better to have a few reliable tests than many unreliable ones. ## 🚀 2. Continuous Delivery (CD) - From Code to Customer CD ensures your software ...

Ultimate Guide to Sending Data in React: Axios & Fetch Explained

Ultimate Guide to Sending Data in React using Axios and Fetch Whether you're building a login form, uploading files, or submitting a complex dataset to your backend, understanding how to send data in React is essential. In this comprehensive guide, we'll explore all the major ways to send data using Axios and the native Fetch API , including formats like JSON , form-data , x-www-form-urlencoded , and other advanced techniques. This guide is designed for developers from beginner to advanced levels, providing both theoretical understanding and practical implementation examples. By the end of this tutorial, you'll have a complete understanding of how data flows from React components to backend servers, and you'll know exactly which method to choose for different scenarios. 📌 Why Learn Different Data Formats? Before diving into implementation details, it's crucial to understand why different data formats exist...