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

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 ...

Introduction to Cloud Computing: Revolutionizing the Digital Landscape

In today's rapidly evolving digital world, cloud computing stands as a cornerstone of modern technology, transforming how businesses operate and individuals interact with data. Let's dive deep into this fascinating technology that powers our digital future. ## What is Cloud Computing? Imagine having a virtual supercomputer at your fingertips, accessible from anywhere in the world. That's the essence of cloud computing – a technology that delivers computing services such as storage, databases, software, and processing power over the internet, eliminating the need for physical hardware investments. ## The Three Pillars of Cloud Service Models ### Infrastructure as a Service (IaaS) Think of IaaS as renting the digital building blocks of computing. Companies like Amazon Web Services (AWS) and Microsoft Azure provide virtual machines, storage, and networking resources on-demand. This model offers unprecedented flexibility, allowing businesses to scale their infrastructure up or ...

How to Fix "ERESOLVE Unable to Resolve Dependency Tree" Error While Creating a React App

How to Fix Dependency Errors While Creating a React App If you're trying to set up a React app using npx create-react-app and encounter the following error: npm error code ERESOLVE npm error ERESOLVE unable to resolve dependency tree npm error Found: react@19.0.0 npm error Could not resolve dependency: npm error peer react@"^18.0.0" from @testing-library/react@13.4.0 Don't worry! This issue occurs due to dependency conflicts between react , react-dom , and other packages like @testing-library/react . Below are two simple ways to fix this issue. Step 1: Try Fixing It With npm Before switching to Yarn, you can resolve the issue by installing the missing or incompatible dependencies manually. Here's how: After running npx create-react-app my-app , if the error appears, navigate to your project folder: cd my-app Install the missing web-vitals dependency: npm install web-vitals Check for other dependency ...