Next.js course Β· Module 9: Integrations and Advanced Features

Next.js and Strapi - A Powerful Frontend and Headless CMS Combination

8 min read Β·
In this lesson9

In Quantum Metropolis, where frontend and backend technologies merge into a harmonious whole, you will discover one of the most powerful combinations in modern web development - Next.js with Strapi. This duo allows you to build scalable, performant applications with full content control.

What is Strapi?

Strapi is an open-source headless CMS (Content Management System) that provides a RESTful or GraphQL API for content management. Unlike traditional CMSs like WordPress, Strapi does not impose any frontend structure - you decide how to display the data.

Key features of Strapi:

  • 100% JavaScript - written in Node.js
  • Customizable - full control over data structure
  • Self-hosted or Cloud - choose your hosting method
  • RESTful & GraphQL API - flexible data access
  • Admin Panel - intuitive management interface
  • Roles-Based Access Control - advanced permission management

Why Next.js + Strapi?

Combining Next.js with Strapi creates a complete stack for building modern web applications:

  1. Separation of concerns - frontend and backend are independent
  2. Performance - static generation with dynamic content
  3. Developer Experience - both tools are developer-friendly
  4. Scalability - easy scaling of each layer separately
  5. TypeScript support - full typing support

Installing and configuring Strapi

Step 1: Creating a new Strapi project

# Create a new Strapi project
npx create-strapi-app@latest my-strapi-backend --quickstart

# Or with TypeScript
npx create-strapi-app@latest my-strapi-backend --typescript

After installation, Strapi will automatically run on http://localhost:1337. Your first visit will redirect you to the admin account creation panel.

Step 2: Configuring Content Types

In the Strapi admin panel, you can create data structures (Content Types) using the intuitive Content-Type Builder:

  1. Go to Content-Type Builder
  2. Click Create new collection type
  3. Name your collection (e.g., "Article")
  4. Add fields:
    • title (Text)
    • content (Rich text)
    • slug (UID)
    • featuredImage (Media)
    • author (Relation to Users)
    • publishedAt (Datetime)

Step 3: Configuring API permissions

By default, Strapi blocks public access to the API. To enable data reading:

  1. Go to Settings β†’ Roles β†’ Public
  2. For your Content Type, select the appropriate permissions (e.g. find and findOne)
  3. Save the changes

Integrating Next.js with Strapi

Step 1: Preparing the Next.js project

# In a new terminal, create a Next.js project
npx create-next-app@latest my-nextjs-frontend --typescript --tailwind --app

cd my-nextjs-frontend

Step 2: Environment variables configuration

Create the file .env.local:

NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337
STRAPI_API_TOKEN=your-api-token-here

Step 3: Creating the API client

Create helper functions for communicating with Strapi:

// lib/strapi.ts
interface StrapiResponse<T> {
  data: T;
  meta: {
    pagination?: {
      page: number;
      pageSize: number;
      pageCount: number;
      total: number;
    };
  };
}

const strapiUrl = process.env.NEXT_PUBLIC_STRAPI_API_URL || 'http://localhost:1337';

export async function fetchAPI<T>(
  path: string,
  urlParamsObject: Record<string, any> = {},
  options: RequestInit = {}
): Promise<T> {
  // Merge default and user options
  const mergedOptions: RequestInit = {
    headers: {
      "Content-Type": "application/json",
      ...(process.env.STRAPI_API_TOKEN && {
        Authorization: `Bearer ${process.env.STRAPI_API_TOKEN}`,
      }),
    },
    ...options,
  };

  // Build request URL
  const queryString = new URLSearchParams(urlParamsObject).toString();
  const requestUrl = `${strapiUrl}${path}${queryString ? `?${queryString}` : ""}`;

  // Trigger API call
  const response = await fetch(requestUrl, mergedOptions);
  const data = await response.json();

  if (!response.ok) {
    throw new Error(`API call failed: ${response.status}`);
  }

  return data;
}

// Helper to get media URL
export function getStrapiMedia(url: string | null) {
  if (url == null) return null;
  if (url.startsWith("http") || url.startsWith("//")) return url;
  return `${strapiUrl}${url}`;
}

Fetching data from Strapi in Next.js

Static Site Generation (SSG)

Use generateStaticParams and async functions in components:

// app/articles/page.tsx
import { fetchAPI } from '@/lib/strapi';

interface Article {
  id: number;
  attributes: {
    title: string;
    slug: string;
    content: string;
    publishedAt: string;
    featuredImage: {
      data: {
        attributes: {
          url: string;
          alternativeText: string;
        };
      };
    };
  };
}

async function getArticles() {
  const articlesRes = await fetchAPI<StrapiResponse<Article[]>>('/api/articles', {
    populate: {
      featuredImage: {
        fields: ['url', 'alternativeText']
      },
      author: {
        fields: ['name', 'email']
      }
    },
    sort: ['publishedAt:desc'],
    pagination: {
      pageSize: 10,
    },
  });

  return articlesRes.data;
}

export default async function ArticlesPage() {
  const articles = await getArticles();

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-4xl font-bold mb-8">Articles</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {articles.map((article) => (
          <article key={article.id} className="border rounded-lg overflow-hidden shadow-lg">
            {article.attributes.featuredImage?.data && (
              <img
                src={getStrapiMedia(article.attributes.featuredImage.data.attributes.url)}
                alt={article.attributes.featuredImage.data.attributes.alternativeText}
                className="w-full h-48 object-cover"
              />
            )}
            <div className="p-4">
              <h2 className="text-xl font-semibold mb-2">
                {article.attributes.title}
              </h2>
              <p className="text-gray-600">
                {new Date(article.attributes.publishedAt).toLocaleDateString('pl-PL')}
              </p>
              <a
                href={`/articles/${article.attributes.slug}`}
                className="text-blue-500 hover:underline mt-2 inline-block"
              >
                Read more β†’
              </a>
            </div>
          </article>
        ))}
      </div>
    </div>
  );
}

Dynamic Routes

For individual articles, use dynamic routes:

// app/articles/[slug]/page.tsx
import { fetchAPI } from '@/lib/strapi';
import { notFound } from 'next/navigation';
import ReactMarkdown from 'react-markdown';

interface ArticlePageProps {
  params: Promise<{
    slug: string;
  }>;
}

async function getArticleBySlug(slug: string) {
  const articlesRes = await fetchAPI<StrapiResponse<Article[]>>('/api/articles', {
    filters: {
      slug: {
        $eq: slug,
      },
    },
    populate: {
      featuredImage: {
        fields: ['url', 'alternativeText']
      },
      author: {
        populate: {
          avatar: {
            fields: ['url']
          }
        }
      }
    },
  });

  if (!articlesRes.data || articlesRes.data.length === 0) {
    return null;
  }

  return articlesRes.data[0];
}

export async function generateStaticParams() {
  const articlesRes = await fetchAPI<StrapiResponse<Article[]>>('/api/articles', {
    fields: ['slug'],
    pagination: {
      pageSize: 100,
    },
  });

  return articlesRes.data.map((article) => ({
    slug: article.attributes.slug,
  }));
}

export default async function ArticlePage({ params }: ArticlePageProps) {
  const article = await getArticleBySlug((await params).slug);

  if (!article) {
    notFound();
  }

  return (
    <article className="container mx-auto px-4 py-8 max-w-4xl">
      {article.attributes.featuredImage?.data && (
        <img
          src={getStrapiMedia(article.attributes.featuredImage.data.attributes.url)}
          alt={article.attributes.featuredImage.data.attributes.alternativeText}
          className="w-full h-96 object-cover rounded-lg mb-8"
        />
      )}

      <h1 className="text-4xl font-bold mb-4">{article.attributes.title}</h1>

      <div className="flex items-center gap-4 mb-8 text-gray-600">
        <span>Author: {article.attributes.author?.data?.attributes.name}</span>
        <span>β€’</span>
        <time>
          {new Date(article.attributes.publishedAt).toLocaleDateString('pl-PL')}
        </time>
      </div>

      <div className="prose prose-lg max-w-none">
        <ReactMarkdown>{article.attributes.content}</ReactMarkdown>
      </div>
    </article>
  );
}

Advanced features

Real-time updates with webhooks

Strapi can send webhooks when content changes. Configure an endpoint in Next.js:

// app/api/revalidate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath, revalidateTag } from 'next/cache';

export async function POST(request: NextRequest) {
  const body = await request.json();
  const secret = request.headers.get('x-strapi-signature');

  // Verify the webhook signature
  if (secret !== process.env.STRAPI_WEBHOOK_SECRET) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    // Revalidate appropriate paths based on the event
    switch (body.event) {
      case 'entry.create':
      case 'entry.update':
        if (body.model === 'article') {
          revalidatePath('/articles');
          revalidatePath(`/articles/${body.entry.slug}`);
        }
        break;
      case 'entry.delete':
        if (body.model === 'article') {
          revalidatePath('/articles');
        }
        break;
    }

    return NextResponse.json({ revalidated: true });
  } catch (error) {
    return NextResponse.json({ error: 'Error revalidating' }, { status: 500 });
  }
}

GraphQL integration

Strapi also offers a GraphQL API. Install the plugin:

# In the Strapi folder
npm install @strapi/plugin-graphql

Then use GraphQL in Next.js:

// lib/graphql.ts
import { GraphQLClient } from 'graphql-request';

const client = new GraphQLClient(`${process.env.NEXT_PUBLIC_STRAPI_API_URL}/graphql`, {
  headers: {
    authorization: process.env.STRAPI_API_TOKEN
      ? `Bearer ${process.env.STRAPI_API_TOKEN}`
      : '',
  },
});

export async function queryStrapi<T>(query: string, variables?: any): Promise<T> {
  return client.request<T>(query, variables);
}

Image optimization

Integrate Strapi with Next.js Image Optimization:

// components/StrapiImage.tsx
import Image from 'next/image';
import { getStrapiMedia } from '@/lib/strapi';

interface StrapiImageProps {
  src: string;
  alt: string;
  width: number;
  height: number;
  className?: string;
}

export default function StrapiImage({ src, alt, ...props }: StrapiImageProps) {
  const imageUrl = getStrapiMedia(src);

  if (!imageUrl) {
    return null;
  }

  return (
    <Image
      src={imageUrl}
      alt={alt}
      {...props}
      loader={({ src, width, quality }) => {
        const params = new URLSearchParams();
        if (width) params.set('width', width.toString());
        if (quality) params.set('quality', quality.toString());
        return `${src}?${params.toString()}`;
      }}
    />
  );
}

Preview mode

Implement preview for unpublished content:

// app/api/preview/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { draftMode } from 'next/headers';

export async function GET(request: NextRequest) {
  const secret = request.nextUrl.searchParams.get('secret');
  const slug = request.nextUrl.searchParams.get('slug');

  if (secret !== process.env.STRAPI_PREVIEW_SECRET || !slug) {
    return NextResponse.json({ message: 'Invalid token' }, { status: 401 });
  }

  // Enable Draft Mode
  (await draftMode()).enable();

  // Redirect to the preview page
  return NextResponse.redirect(new URL(`/articles/${slug}`, request.url));
}

// app/api/exit-preview/route.ts
export async function GET() {
  (await draftMode()).disable();
  return NextResponse.redirect('/');
}

Deployment and best practices

1. Environment Variables

Always use environment variables for sensitive data:

# .env.production
NEXT_PUBLIC_STRAPI_API_URL=https://your-strapi-instance.com
STRAPI_API_TOKEN=your-production-token
STRAPI_WEBHOOK_SECRET=your-webhook-secret
STRAPI_PREVIEW_SECRET=your-preview-secret

2. Caching Strategy

Use Next.js caching:

// Cache for 60 seconds
export const revalidate = 60;

// Or use cache tags
fetch(url, { next: { tags: ['articles'] } });

3. Error Handling

Implement robust error handling:

export async function getArticles() {
  try {
    const data = await fetchAPI<StrapiResponse<Article[]>>('/api/articles');
    return data;
  } catch (error) {
    console.error('Error fetching articles:', error);
    return { data: [], meta: {} };
  }
}

4. TypeScript Types

Generate types from the Strapi schema:

# Install the type generator
npm install -D @strapi/types

Summary

Combining Next.js with Strapi creates a powerful stack for building modern web applications. Strapi provides a flexible API and intuitive content management system, while Next.js delivers a performant frontend with SSG/SSR and optimizations.

This combination is ideal for:

  • Blogs and news portals
  • E-commerce
  • Portfolios and corporate websites
  • SaaS applications
  • Educational platforms

In the following modules, we will explore more advanced topics such as multi-tenancy, internationalization, and custom plugins in Strapi.

Code for this lesson: App.tsx
import React, { useState } from 'react';

interface Article {
  id: number;
  title: string;
  slug: string;
  content: string;
  author: string;
  publishedAt: string;
  category: string;
}

const mockArticles: Article[] = [
  { id: 1, title: 'Introduction to Headless CMS', slug: 'intro-headless-cms', content: 'Headless CMS separates the backend from the frontend, giving full control over content presentation...', author: 'Admin', publishedAt: '2025-01-15', category: 'CMS' },
  { id: 2, title: 'Strapi and Next.js - Getting Started', slug: 'strapi-nextjs-start', content: 'Integrating Strapi with Next.js allows building performant applications with dynamic content...', author: 'Developer', publishedAt: '2025-02-10', category: 'Tutorial' },
  { id: 3, title: 'REST vs GraphQL in Strapi', slug: 'rest-vs-graphql', content: 'Strapi offers both REST API and GraphQL. Each approach has its advantages...', author: 'Admin', publishedAt: '2025-03-05', category: 'API' },
  { id: 4, title: 'Typing Strapi Responses in TypeScript', slug: 'strapi-typescript', content: 'With TypeScript we can type Strapi API responses for better DX...', author: 'Developer', publishedAt: '2025-03-20', category: 'TypeScript' },
];

const StrapiDemo = () => {
  const [articles] = useState<Article[]>(mockArticles);
  const [selected, setSelected] = useState<Article | null>(null);
  const [endpoint, setEndpoint] = useState('/api/articles');
  const [response, setResponse] = useState<string>('');

  const simulateFetch = () => {
    const isDetail = endpoint.includes('/api/articles/');
    const slug = endpoint.split('/api/articles/')[1];

    if (isDetail && slug) {
      const found = articles.find(a => a.slug === slug);
      if (found) {
        setResponse(JSON.stringify({ data: { id: found.id, attributes: { title: found.title, content: found.content, slug: found.slug, author: found.author, publishedAt: found.publishedAt } }, meta: {} }, null, 2));
        setSelected(found);
      } else {
        setResponse(JSON.stringify({ error: { status: 404, message: 'Not found' } }, null, 2));
      }
    } else {
      setResponse(JSON.stringify({ data: articles.map(a => ({ id: a.id, attributes: { title: a.title, slug: a.slug, category: a.category, publishedAt: a.publishedAt } })), meta: { pagination: { page: 1, pageSize: 25, total: articles.length } } }, null, 2));
      setSelected(null);
    }
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'sans-serif' }}>
      <h1 style={{ color: '#64ffda', textAlign: 'center' }}>Next.js + Strapi CMS</h1>
      <p style={{ textAlign: 'center', color: '#888', marginBottom: '20px' }}>Headless CMS API Simulation</p>

      <div style={{ maxWidth: '800px', margin: '0 auto' }}>
        <div style={{ background: 'rgba(255,255,255,0.05)', padding: '16px', borderRadius: '10px', marginBottom: '16px', border: '1px solid #333' }}>
          <h3 style={{ color: '#7c4dff', marginBottom: '10px' }}>API Explorer</h3>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '10px' }}>
            <input value={endpoint} onChange={e => setEndpoint(e.target.value)}
              style={{ flex: 1, padding: '10px', background: '#16213e', border: '1px solid #444', borderRadius: '6px', color: '#fff', fontFamily: 'monospace' }} />
            <button onClick={simulateFetch} style={{ padding: '10px 20px', background: '#7c4dff', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
              GET
            </button>
          </div>
          <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
            <button onClick={() => setEndpoint('/api/articles')} style={{ padding: '4px 10px', background: 'rgba(100,255,218,0.1)', border: '1px solid #64ffda', borderRadius: '4px', color: '#64ffda', cursor: 'pointer', fontSize: '12px' }}>/api/articles</button>
            {articles.map(a => (
              <button key={a.id} onClick={() => setEndpoint('/api/articles/' + a.slug)} style={{ padding: '4px 10px', background: 'rgba(124,77,255,0.1)', border: '1px solid #7c4dff', borderRadius: '4px', color: '#7c4dff', cursor: 'pointer', fontSize: '12px' }}>
                /articles/{a.slug}
              </button>
            ))}
          </div>
        </div>

        {response && (
          <div style={{ background: '#000', padding: '16px', borderRadius: '10px', marginBottom: '16px' }}>
            <h4 style={{ color: '#4caf50', marginBottom: '8px' }}>Response:</h4>
            <pre style={{ color: '#0f0', fontSize: '12px', overflow: 'auto', maxHeight: '250px', whiteSpace: 'pre-wrap' }}>{response}</pre>
          </div>
        )}

        {selected && (
          <div style={{ background: 'rgba(255,255,255,0.05)', padding: '20px', borderRadius: '10px', border: '1px solid #333' }}>
            <span style={{ color: '#7c4dff', fontSize: '12px' }}>{selected.category}</span>
            <h2 style={{ color: '#64ffda', margin: '8px 0' }}>{selected.title}</h2>
            <p style={{ color: '#aaa', fontSize: '13px' }}>By {selected.author} | {selected.publishedAt}</p>
            <p style={{ color: '#ccc', marginTop: '12px', lineHeight: '1.6' }}>{selected.content}</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default StrapiDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What data does Strapi return by default through its REST API?

  2. 2. Which of the following features BEST describes a Headless CMS?

Hands-on tasks in the game

  • Click in order

    Arrange the steps of integrating Next.js with Strapi in order.

  • Code editor

    Create a component that fetches data from headless CMS Strapi in Next.js

  • Code editor

    Create an Article content type with title, content, and slug fields.

  1. QuestionData from Strapi API
  2. QuestionHeadless CMS Features
  3. Click in orderNext.js and Strapi Integration
  4. Coding taskPractice: Strapi Integration with Next.js
  5. Coding taskStrapi API Configuration

Useful articles