Kurs Next.js · Moduł 9: Integracje i zaawansowane funkcje
Next.js i Strapi - Potężne połączenie frontend i headless CMS
W tej lekcji9
W Metropolii Quantum, gdzie technologie frontend i backend łączą się w harmonijną całość, poznasz jedno z najpotężniejszych połączeń współczesnego web developmentu - Next.js ze Strapi. To duet, który pozwala budować skalowalne, wydajne aplikacje z pełną kontrolą nad treścią.
Czym jest Strapi?
Strapi to open-source'owy headless CMS (Content Management System), który dostarcza RESTful lub GraphQL API do zarządzania treścią. W przeciwieństwie do tradycyjnych CMS-ów jak WordPress, Strapi nie narzuca żadnej struktury frontend - to ty decydujesz, jak wyświetlać dane.
Kluczowe cechy Strapi:
- 100% JavaScript - napisany w Node.js
- Customizable - pełna kontrola nad strukturą danych
- Self-hosted lub Cloud - wybierz sposób hostingu
- RESTful & GraphQL API - elastyczny dostęp do danych
- Admin Panel - intuicyjny interfejs zarządzania
- Role-Based Access Control - zaawansowane zarządzanie uprawnieniami
Dlaczego Next.js + Strapi?
Połączenie Next.js ze Strapi tworzy kompletny stack do budowania nowoczesnych aplikacji webowych:
- Separacja concerns - frontend i backend są niezależne
- Performance - statyczne generowanie z dynamiczną treścią
- Developer Experience - oba narzędzia są przyjazne dla programistów
- Scalability - łatwe skalowanie każdej warstwy osobno
- TypeScript support - pełne wsparcie dla typowania
Instalacja i konfiguracja Strapi
Krok 1: Tworzenie nowego projektu Strapi
# Utwórz nowy projekt Strapi
npx create-strapi-app@latest my-strapi-backend --quickstart
# Lub z TypeScript
npx create-strapi-app@latest my-strapi-backend --typescriptPo instalacji Strapi automatycznie uruchomi się na http://localhost:1337. Pierwsza wizyta przekieruje cię do panelu tworzenia konta administratora.
Krok 2: Konfiguracja Content Types
W panelu admina Strapi możesz utworzyć struktury danych (Content Types) używając intuicyjnego Content-Type Builder:
- Przejdź do Content-Type Builder
- Kliknij Create new collection type
- Nazwij swoją kolekcję (np. "Article")
- Dodaj pola:
title(Text)content(Rich text)slug(UID)featuredImage(Media)author(Relation to Users)publishedAt(Datetime)
Krok 3: Konfiguracja API permissions
Domyślnie Strapi blokuje publiczny dostęp do API. Aby umożliwić odczyt danych:
- Przejdź do Settings → Roles → Public
- Dla swojego Content Type zaznacz odpowiednie uprawnienia (np.
findifindOne) - Zapisz zmiany
Integracja Next.js ze Strapi
Krok 1: Przygotowanie projektu Next.js
# W nowym terminalu, utwórz projekt Next.js
npx create-next-app@latest my-nextjs-frontend --typescript --tailwind --app
cd my-nextjs-frontendKrok 2: Konfiguracja zmiennych środowiskowych
Utwórz plik .env.local:
NEXT_PUBLIC_STRAPI_API_URL=http://localhost:1337
STRAPI_API_TOKEN=your-api-token-hereKrok 3: Tworzenie klienta API
Stwórz pomocnicze funkcje do komunikacji ze 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}`;
}Pobieranie danych ze Strapi w Next.js
Static Site Generation (SSG)
Wykorzystaj generateStaticParams i funkcje asynchroniczne w komponentach:
// 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">Artykuły</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"
>
Czytaj więcej →
</a>
</div>
</article>
))}
</div>
</div>
);
}Dynamic Routes
Dla pojedynczych artykułów użyj 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>Autor: {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>
);
}Zaawansowane funkcjonalności
Real-time updates z webhooks
Strapi może wysyłać webhooks przy zmianach w contencie. Skonfiguruj endpoint w 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');
// Weryfikuj webhook signature
if (secret !== process.env.STRAPI_WEBHOOK_SECRET) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
// Rewaliduj odpowiednie ścieżki na podstawie eventu
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 oferuje również GraphQL API. Zainstaluj plugin:
# W folderze Strapi
npm install @strapi/plugin-graphqlNastępnie użyj GraphQL w 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);
}Optymalizacja obrazów
Integruj Strapi z 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
Implementuj podgląd nieopublikowanych treści:
// 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 i najlepsze praktyki
1. Environment Variables
Zawsze używaj zmiennych środowiskowych dla wrażliwych danych:
# .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-secret2. Caching Strategy
Wykorzystaj Next.js caching:
// Cache na 60 sekund
export const revalidate = 60;
// Lub użyj cache tags
fetch(url, { next: { tags: ['articles'] } });3. Error Handling
Implementuj solidną obsługę błędów:
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
Generuj typy ze Strapi schema:
# Zainstaluj generator typów
npm install -D @strapi/typesPodsumowanie
Połączenie Next.js ze Strapi tworzy potężny stack do budowania nowoczesnych aplikacji webowych. Strapi dostarcza elastyczne API i intuicyjny system zarządzania treścią, podczas gdy Next.js zapewnia wydajny frontend z SSG/SSR i optymalizacjami.
Ta kombinacja jest idealna dla:
- Blogów i portali informacyjnych
- E-commerce
- Portfolio i stron korporacyjnych
- Aplikacji SaaS
- Platform edukacyjnych
W następnych modułach zgłębimy bardziej zaawansowane tematy, takie jak multi-tenancy, internationalization i custom plugins w Strapi.
Kod do tej lekcji: 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: 'Wprowadzenie do Headless CMS', slug: 'intro-headless-cms', content: 'Headless CMS oddziela backend od frontendu, dając pełną kontrolę nad prezentacją treści...', author: 'Admin', publishedAt: '2025-01-15', category: 'CMS' },
{ id: 2, title: 'Strapi i Next.js - Pierwsze kroki', slug: 'strapi-nextjs-start', content: 'Integracja Strapi z Next.js pozwala na budowanie wydajnych aplikacji z dynamiczną treścią...', author: 'Developer', publishedAt: '2025-02-10', category: 'Tutorial' },
{ id: 3, title: 'REST vs GraphQL w Strapi', slug: 'rest-vs-graphql', content: 'Strapi oferuje zarówno REST API jak i GraphQL. Każde podejście ma swoje zalety...', author: 'Admin', publishedAt: '2025-03-05', category: 'API' },
{ id: 4, title: 'Typowanie odpowiedzi Strapi w TypeScript', slug: 'strapi-typescript', content: 'Dzięki TypeScript możemy typować odpowiedzi z API Strapi dla lepszego 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' }}>Symulacja headless CMS API</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;Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jakie dane Strapi domyślnie zwraca przez REST API?
2. Która z poniższych cech NAJLEPIEJ opisuje Headless CMS?
Zadania praktyczne w grze
- Klikanie w kolejności
Uporządkuj kroki integracji Next.js ze Strapi.
- Edytor kodu
Stwórz komponent pobierający dane z headless CMS Strapi w Next.js
- Edytor kodu
Stwórz Article content type z polami title, content, slug.