Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Strapi + Next.js App Router: Using Fetch, SWR and React Query

Hey there, fellow code warriors! Today, we’re diving into the exciting world of headless CMS and modern web frameworks. I’m gonna show you how to hook up Strapi CMS with Next.js App Router using three different data fetching methods. Trust me, by the end of this, you’ll be slinging content like a pro! 💪

The Setup

First things first, let’s get our project off the ground:

npx create-next-app@latest my-strapi-nextjs-app
cd my-strapi-nextjs-app
npm install swr react-query

Now, let’s assume you’ve got Strapi running locally on port 1337 with some sweet, sweet content ready to go.

Method 1: Raw and Rugged with Fetch 🦁

Alright, let’s kick it old school with the built-in fetch API. Create a new file app/page.js:

async function getArticles() {
  const res = await fetch('http://localhost:1337/api/articles');
  if (!res.ok) throw new Error('Failed to fetch articles');
  return res.json();
}

export default async function Home() {
  const { data } = await getArticles();
  
  return (
    <main>
      <h1>My Awesome Blog</h1>
      {data.map(article => (
        <article key={article.id}>
          <h2>{article.attributes.title}</h2>
          <p>{article.attributes.content}</p>
        </article>
      ))}
    </main>
  );
}

Boom! 💥 We’re fetching articles like it’s nobody’s business. But wait, there’s more!

Method 2: SWR – Stale-While-Revalidate Magic ✨

Let’s level up our game with SWR. Create a new file app/swr-page.js:

'use client';

import useSWR from 'swr';

const fetcher = (...args) => fetch(...args).then(res => res.json());

export default function SWRPage() {
  const { data, error } = useSWR('http://localhost:1337/api/articles', fetcher);

  if (error) return <div>Failed to load</div>;
  if (!data) return <div>Loading...</div>;

  return (
    <main>
      <h1>SWR-Powered Blog</h1>
      {data.data.map(article => (
        <article key={article.id}>
          <h2>{article.attributes.title}</h2>
          <p>{article.attributes.content}</p>
        </article>
      ))}
    </main>
  );
}

SWR’s got our back with automatic revalidation and a slick loading state. It’s like your data’s got a mind of its own! 🧠

Method 3: React Query – The Data-Fetching Powerhouse 💪

Time to bring out the big guns. Let’s set up React Query in app/layout.js:

'use client';

import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <QueryClientProvider client={queryClient}>
        <body>{children}</body>
      </QueryClientProvider>
    </html>
  );
}

Now, let’s create app/react-query-page.js:

'use client';

import { useQuery } from 'react-query';

const fetchArticles = async () => {
  const res = await fetch('http://localhost:1337/api/articles');
  if (!res.ok) throw new Error('Network response was not ok');
  return res.json();
};

export default function ReactQueryPage() {
  const { data, isLoading, error } = useQuery('articles', fetchArticles);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;

  return (
    <main>
      <h1>React Query Blog Extravaganza</h1>
      {data.data.map(article => (
        <article key={article.id}>
          <h2>{article.attributes.title}</h2>
          <p>{article.attributes.content}</p>
        </article>
      ))}
    </main>
  );
}

React Query’s bringing the heat with powerful caching and invalidation strategies. It’s like your data’s got a personal trainer! 💪

The Wrap-Up

And there you have it, folks! We’ve just turbocharged our Next.js app with Strapi CMS using three different data-fetching approaches. Each method has its own superpowers:

  • fetch: Simple and built-in, perfect for static pages.
  • SWR: Lightweight and ideal for real-time data.
  • React Query: The heavy-hitter for complex data management.

Now, go forth and build some killer content-driven apps! Remember, with great power comes great responsibility… to create awesome user experiences! 😎

Happy coding, and may your builds always be successful! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *