Skip to content

Kapitel 16: Erweiterte Lernrichtungen

📖 Lernziele

In diesem Kapitel lernen Sie:

  • ✅ Next.js Ökosystem erkunden (offizielle Plugins & Community-Module)
  • ✅ Mobile Optimierung mit Next.js + Tailwind CSS
  • ✅ TypeScript mit Next.js integrieren (fortgeschritten)
  • ✅ Backend-Integration (Next.js + Node.js/Express Full-Stack)
  • ✅ Next.js 15 neue Funktionen (zukunftssicher)

16.1 Next.js Ökosystem erweitern

🌍 Offizielle Plugins & Module

Plugin/ModulZweckWebseite
@next/bundle-analyzerBundle-Größe analysierenOffiziell
next-sitemapSitemap.xml automatisch generierenCommunity
next-seoSEO-Optimierung vereinfachenCommunity
next-authAuthentifizierung (OAuth, JWT)Offiziell empfohlen
next-i18nextInternationalisierung (i18n)Community

📝 Beispiel: next-sitemap installieren

bash
pnpm add next-sitemap

Konfiguration (next-sitemap.config.js):

javascript
/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: 'https://www.deine-domain.de',
  generateRobotsTxt: true,
  robotsTxtOptions: {
    policies: [
      {
        userAgent: '*',
        allow: '/',
      },
    ],
  },
};

Skript (package.json):

json
{
  "scripts": {
    "postbuild": "next-sitemap"
  }
}

16.2 Mobile Optimierung

📱 Responsive Design mit Tailwind CSS

Beispiel:

jsx
export default function MobileFriendlyPage() {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      <div className="p-4 bg-white rounded-lg shadow">
        <h2 className="text-xl font-bold">Karte 1</h2>
        <p className="text-gray-600">Responsive Inhalt...</p>
      </div>
      {/* Weitere Karten */}
    </div>
  );
}

🎯 Mobile-First Ansatz

BreakpointTailwind PräfixBedeutung
Smsm:≥ 640px (Tablets)
Mdmd:≥ 768px (Tablets quer)
Lglg:≥ 1024px (Laptops)
Xlxl:≥ 1280px (Desktops)

Beispiel:

jsx
{/* Mobile: volle Breite, ab md: halbe Breite */}
<div className="w-full md:w-1/2 lg:w-1/3">
  Inhalt
</div>

16.3 TypeScript mit Next.js (Fortgeschritten)

📘 Warum TypeScript?

VorteilErklärung
TypsicherheitFehler werden zur Compile-Zeit erkannt
Bessere IDE-UnterstützungAutovervollständigung, Refactoring
Self-Dokumentierender CodeSchnelleres Verständnis für Teammitglieder

🛠️ TypeScript in Next.js integrieren

Schritt 1: Installation

bash
pnpm add -D typescript @types/react @types/node

Schritt 2: tsconfig.json generieren

bash
touch tsconfig.json
npm run dev  # Next.js generiert automatisch die Konfiguration

Schritt 3: .js zu .tsx umbenennen

Beispiel (app/page.tsx):

tsx
interface Post {
  id: number;
  title: string;
  content: string;
}

async function getPosts(): Promise<Post[]> {
  const res = await fetch('https://api.example.com/posts');
  return res.json();
}

export default async function HomePage() {
  const posts: Post[] = await getPosts();
  
  return (
    <main>
      <h1>Blog-Artikel</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}

📝 Typisierung von API-Routen

Beispiel (app/api/users/route.ts):

typescript
import { NextResponse } from 'next/server';

interface User {
  id: number;
  name: string;
  email: string;
}

export async function GET() {
  const users: User[] = [
    { id: 1, name: 'Max', email: 'max@example.com' },
  ];
  
  return NextResponse.json(users);
}

export async function POST(request: Request) {
  const body: User = await request.json();
  
  // Validierung
  if (!body.name || !body.email) {
    return NextResponse.json(
      { error: 'Name und Email erforderlich' },
      { status: 400 }
    );
  }
  
  // Speichern...
  return NextResponse.json(body, { status: 201 });
}

16.4 Backend-Integration (Full-Stack)

🔗 Next.js + Node.js/Express

Szenario: Next.js Frontend + separater Express-Backend.

Backend (server.js):

javascript
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

app.get('/api/users', (req, res) => {
  res.json([
    { id: 1, name: 'Max' },
    { id: 2, name: 'Anna' },
  ]);
});

app.listen(4000, () => {
  console.log('Backend läuft auf Port 4000');
});

Frontend (app/page.js):

jsx
async function getUsers() {
  const res = await fetch('http://localhost:4000/api/users');
  return res.json();
}

export default async function HomePage() {
  const users = await getUsers();
  
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Proxy-Konfiguration (next.config.js):

javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:4000/api/:path*',
      },
    ];
  },
};

module.exports = nextConfig;

16.5 Next.js 15 neue Funktionen (Vorausschau)

🚀 Next.js 15 (Vorausschau)

FunktionBeschreibungStatus
Turbopack (Stable)Neuer Bundler (极度 schnell)✅ Stabil in v15
Server Actions (Stable)Formular-Handling auf Server✅ Stabil in v15
Partial Prerendering (PPR)Hybrides Rendering⚠️ Experimentell
use cache DirectiveFeingranulares Caching⚠️ Experimentell

📝 Turbopack Beispiel

bash
# Next.js 15 mit Turbopack
npm run dev -- --turbo

Ergebnis:

▲ Next.js 15.0.0 (Turbopack)
- Local:        http://localhost:3000
✓ 700x schnellerer Bundler

📝 Zusammenfassung

In diesem Kapitel haben Sie gelernt:

KonzeptErklärung
ÖkosystemOffizielle & Community-Plugins
MobileResponsive Design mit Tailwind CSS
TypeScriptTypsicherheit für Next.js
BackendFull-Stack mit Express
Next.js 15Turbopack, Server Actions

✅ Nächste Schritte

  1. Übung: Integrieren Sie TypeScript in Ihr Next.js-Projekt
  2. Übung: Erstellen Sie ein Full-Stack-Projekt (Next.js + Express)
  3. Weiter geht's: Kapitel 17 - Lernressourcen

🎯 Selbsttest

Frage 1: Welches Plugin generiert automatisch eine Sitemap?

Antwort anzeigen `next-sitemap`

Frage 2: Was ist der Vorteil von TypeScript in Next.js?

Antwort anzeigen Typsicherheit, bessere IDE-Unterstützung, self-dokumentierender Code.

Frage 3: Was ist Turbopack?

Antwort anzeigen Ein neuer, extrem schneller Bundler für Next.js (700x schneller als Webpack).

🚀 Weiter zu Kapitel 17: Lernressourcen

Frei für alle Anfänger