Alle Artikel
Next.js5 min

Next.js & Laravel Full Stack: Production-Ready 2025

Die Kombination aus Next.js Laravel Full Stack ist 2025 eine der beliebtesten Architekturen für moderne Webanwendungen. Laravel liefert ein robustes Backend mit API-Routen, Eloquent ORM und umfassender Authentifizierung. Next.js bringt Server-Side Rendering, React 18 Features und optimale Performance für das Frontend. In diesem Tutorial zeige ich dir, wie du einen Next.js Laravel Full Stack aufbaust – production-ready und skalierbar.

Warum Next.js Laravel Full Stack?

Laravel ist seit Jahren der Standard für PHP-Entwicklung. Die Framework-Architektur, Laravel Sanctum für API-Authentifizierung und die Migration-Verwaltung machen Backend-Entwicklung produktiv. Next.js ergänzt dies mit:

  • App Router (seit Next.js 13+) mit Server Components
  • TypeScript-Support out of the box
  • Image-Optimierung und automatisches Code-Splitting
  • Edge Functions für globale Performance

Die Next.js Laravel Full Stack Architektur trennt Frontend und Backend sauber. Das Backend läuft auf einer Subdomain (z.B. api.domain.de), das Frontend auf der Hauptdomain. Diese Trennung ermöglicht unabhängige Deployments und einfacheres Scaling.

Laravel Backend Setup

Starten wir mit dem Laravel-Backend. Ich nutze Laravel 11 (aktuellste Version 2025):

composer create-project laravel/laravel backend-api
cd backend-api
php artisan install:api

Der install:api Befehl richtet Laravel Sanctum ein – das Standard-Tool für SPA-Authentifizierung. Konfiguriere danach .env:

APP_URL=http://localhost:8000
FRONTEND_URL=http://localhost:3000
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:3000

CORS-Konfiguration für Next.js Laravel Full Stack

Next.js und Laravel laufen auf unterschiedlichen Ports/Domains. CORS muss korrekt konfiguriert sein. In config/cors.php:

return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

supports_credentials ist kritisch – ohne dies funktioniert Cookie-basierte Authentifizierung nicht.

API-Routen und Controller

Erstelle einen simplen API-Controller:

php artisan make:controller Api/PostController

In routes/api.php:

use App\Http\Controllers\Api\PostController;

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('posts', PostController::class);
});

Route::get('/health', function () {
    return response()->json(['status' => 'ok']);
});

Der /health Endpoint ist nützlich für Monitoring. Der geschützte /posts Endpoint benötigt Authentifizierung.

Next.js Frontend Setup

Jetzt das Next.js Frontend mit TypeScript:

npx create-next-app@latest frontend --typescript --tailwind --app
cd frontend
npm install axios

Ich nutze Axios für HTTP-Requests, da es Interceptors und bessere Error-Handling bietet als fetch.

API-Client mit TypeScript

Erstelle lib/api.ts für zentralisierte API-Calls:

import axios from 'axios';

const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000',
  withCredentials: true,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
});

// CSRF-Token holen vor POST/PUT/DELETE
api.interceptors.request.use(async (config) => {
  if (['post', 'put', 'delete', 'patch'].includes(config.method || '')) {
    await axios.get('http://localhost:8000/sanctum/csrf-cookie', {
      withCredentials: true,
    });
  }
  return config;
});

export default api;

Der Interceptor holt automatisch das CSRF-Token von Laravel Sanctum. Das ist eine Next.js Laravel Full Stack Best Practice.

Server Components für Data Fetching

Next.js App Router ermöglicht Server Components – perfekt für initiales Data Fetching:

// app/posts/page.tsx
import api from '@/lib/api';

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

async function getPosts(): Promise<Post[]> {
  try {
    const response = await api.get('/api/posts');
    return response.data;
  } catch (error) {
    console.error('Error fetching posts:', error);
    return [];
  }
}

export default async function PostsPage() {
  const posts = await getPosts();

  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-6">Posts</h1>
      <div className="grid gap-4">
        {posts.map((post) => (
          <article key={post.id} className="border p-4 rounded">
            <h2 className="text-xl font-semibold">{post.title}</h2>
            <p className="text-gray-600">{post.content}</p>
          </article>
        ))}
      </div>
    </div>
  );
}

Server Components fetchen Daten während des Server-Renderings. Kein Loading-State im Browser nötig.

Authentifizierung im Next.js Laravel Full Stack

Laravel Sanctum mit Next.js benötigt Cookie-basierte Authentifizierung. Erstelle lib/auth.ts:

import api from './api';

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

export const authService = {
  async login(email: string, password: string): Promise<User> {
    await api.get('/sanctum/csrf-cookie');
    const response = await api.post('/login', { email, password });
    return response.data.user;
  },

  async register(name: string, email: string, password: string): Promise<User> {
    await api.get('/sanctum/csrf-cookie');
    const response = await api.post('/register', { 
      name, 
      email, 
      password,
      password_confirmation: password 
    });
    return response.data.user;
  },

  async logout(): Promise<void> {
    await api.post('/logout');
  },

  async getUser(): Promise<User | null> {
    try {
      const response = await api.get('/api/user');
      return response.data;
    } catch {
      return null;
    }
  },
};

Laravel liefert standardmäßig /login, /register und /logout Routen. Der /api/user Endpoint gibt den authentifizierten User zurück.

Production Deployment

Für Production empfehle ich:

Laravel Backend:

  • Deploy auf Laravel Forge, Ploi oder DigitalOcean App Platform
  • PHP 8.3+ mit OPcache
  • PostgreSQL oder MySQL (nicht SQLite in Production)
  • Redis für Cache und Sessions
  • SSL-Zertifikat (Let's Encrypt)

Next.js Frontend:

  • Vercel (optimiert für Next.js) oder Netlify
  • Environment Variables setzen: NEXT_PUBLIC_API_URL=https://api.domain.de
  • Edge Network für globale Performance

Wichtige ENV-Variablen:

# Laravel .env
SESSION_DOMAIN=.domain.de
SANCTUM_STATEFUL_DOMAINS=domain.de,www.domain.de

# Next.js
NEXT_PUBLIC_API_URL=https://api.domain.de

Der Punkt vor SESSION_DOMAIN erlaubt Cookies über Subdomains.

Performance-Optimierung

Ein production-ready Next.js Laravel Full Stack braucht Performance-Tuning:

Laravel:

php artisan config:cache
php artisan route:cache
php artisan view:cache
composer install --optimize-autoloader --no-dev

Next.js:

  • Nutze next/image für automatische Bildoptimierung
  • Implementiere Incremental Static Regeneration (ISR) wo möglich
  • Code-Splitting via dynamic imports
import dynamic from 'next/dynamic';

const HeavyComponent = dynamic(() => import('@/components/HeavyComponent'), {
  loading: () => <p>Loading...</p>,
});

Testing der Full Stack Architektur

Für robuste Next.js Laravel Full Stack Anwendungen sind Tests essentiell:

Laravel (PHPUnit):

public function test_authenticated_user_can_fetch_posts()
{
    $user = User::factory()->create();
    
    $response = $this->actingAs($user)
        ->getJson('/api/posts');
    
    $response->assertStatus(200);
}

Next.js (Jest + React Testing Library):

import { render, screen } from '@testing-library/react';
import PostsPage from '@/app/posts/page';

test('renders posts list', async () => {
  render(await PostsPage());
  expect(screen.getByText('Posts')).toBeInTheDocument();
});

Fazit

Die Next.js Laravel Full Stack Architektur kombiniert das Beste aus beiden Welten: Laravels Backend-Power mit Next.js' modernem Frontend. Die Trennung ermöglicht unabhängige Skalierung, klare Verantwortlichkeiten und optimale Developer Experience. Mit Laravel Sanctum für Authentifizierung, TypeScript für Type Safety und Server Components für Performance erhältst du eine production-ready Architektur für 2025.

Die Next.js Laravel Full Stack Lösung eignet sich besonders für SaaS-Anwendungen, E-Commerce-Plattformen und Content-Management-Systeme, die moderne UX mit robuster Backend-Logik verbinden müssen.

Du arbeitest an einem Next.js Laravel Full Stack Projekt? Ich helfe dir gerne bei Architektur-Entscheidungen, Performance-Optimierung oder dem kompletten Setup.

Next.js Laravel Full StackNext.jsFreelancerWebentwicklungDüsseldorf