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