DEV Community

Joodi
Joodi

Posted on

9 1 1 1 1

Fetching Data with Axios in Next.js 15: A Complete Guide

In Next.js 15, fetching data can be done in both Server Components and Client Components, with distinct differences in behavior, performance, and SEO impact. Using Axios for data fetching is a popular choice due to its simplicity and flexibility. In this guide, we’ll explore how to use Axios in both Server and Client Components, the differences between them, and best practices.

Image description


Key Differences Between Server and Client Components

Aspect Server Component Client Component
Rendering Location On the server, before sending HTML to the client. In the browser, after the page has loaded.
SEO Impact SEO-friendly, data is included in initial HTML. Not SEO-friendly, as data is fetched on the client side.
Data in view-source Data is visible in the HTML source. Data is fetched dynamically; not visible in source.
Reactivity Not reactive; designed for static data. Reactive; suited for interactive UI elements.

Using Axios in Server Components

Example: Fetching Data in a Server Component

Server Components fetch data during the server rendering process. This ensures that the data is part of the HTML sent to the browser, which improves SEO.

// app/server-component-example/page.tsx
import axios from 'axios';

type Post = {
  id: number;
  title: string;
  body: string;
};

async function fetchPosts(): Promise<Post[]> {
  const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return response.data;
}

export default async function ServerComponentExample() {
  const posts = await fetchPosts();

  return (
    <div>
      <h1>Server-Fetched Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Key Points

  1. SEO: Data fetched on the server is embedded in the initial HTML, making it visible to search engines and improving SEO.
  2. Source Code Visibility: Data will be visible in the browser's view-source.
  3. Best Use Case: Static or SEO-critical data that does not require frequent updates or interactivity.

Using Axios in Client Components

Example: Fetching Data in a Client Component

Client Components fetch data after the page loads in the browser. This is not SEO-friendly but allows for dynamic and interactive updates.

'use client';

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

type Post = {
  id: number;
  title: string;
  body: string;
};

export default function ClientComponentExample() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchPosts() {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setPosts(response.data);
      } catch (error) {
        console.error('Error fetching posts:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchPosts();
  }, []);

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

  return (
    <div>
      <h1>Client-Fetched Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Key Points

  1. SEO: Data is not part of the initial HTML, so it won’t improve SEO.
  2. Source Code Visibility: Data will not be visible in the view-source.
  3. Reactivity: Ideal for dynamic content that changes frequently or depends on user interactions.

When to Use Server vs. Client Fetching

Use Case Recommended Component
SEO-critical data (e.g., blog posts) Server Component
User-specific or dynamic data Client Component
Frequently updated data Client Component
Static, rarely changing data Server Component

Best Practices for Using Axios in Next.js 15

1. Always Handle Errors Gracefully

Wrap your Axios calls in try-catch blocks to handle errors effectively.

2. Optimize for SEO

Use Server Components for data that impacts SEO. Client Components should be used for data that doesn’t require indexing by search engines.

3. Reduce Redundant Fetching

Avoid duplicating Axios calls across components. Instead, consider using data-fetching libraries like React Query or SWR for caching and synchronization.

4. Security Considerations

Avoid exposing sensitive information in your Axios calls when fetching on the client side, as this data can be inspected in the browser.


SEO Impact of Fetching Data

  • Server Components: Improve SEO by embedding data in the HTML sent to the client. This makes content accessible to search engine crawlers.
  • Client Components: Do not improve SEO, as data is fetched dynamically and not included in the initial HTML.

Conclusion

Fetching data with Axios in Next.js 15 is straightforward and flexible, thanks to the clear separation between Server and Client Components. By understanding the differences and best practices, you can create performant and SEO-friendly applications while delivering dynamic and interactive experiences.

Use Server Components for static and SEO-critical data, and Client Components for dynamic or user-specific data. Always handle errors gracefully and be mindful of your application's performance and security.


I hope you found this helpful! Let’s connect on LinkedIn or GitHub πŸš€

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
mike_adutskevich profile image
Mikhail Adutskevich β€’ β€’ Edited

Hi! What about caching and revalidation in comparison to extended next Fetch api?

Collapse
 
joodi profile image
Joodi β€’

Hi! Thanks for your attention! 😊 I haven’t posted a dedicated post about caching and revalidation yet, but you can check out the official docs here:

πŸ”— nextjs.org/docs/app/building-your-...
πŸ”— nextjs.org/docs/app/building-your-...

Hope this helps! πŸš€

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay