Laravel Inertia.js SSR
Introduction
Inertia.js allows you to build modern single-page applications without building an API. Server-Side Rendering (SSR) enables search engines to crawl your content and improves initial page load performance.
This guide covers setting up Inertia.js with SSR in Laravel applications using React or Vue as the frontend framework.
SSR Setup
Install the Inertia SSR adapter for your frontend:
npm install @inertiajs/ssr
Create the SSR service provider:
php artisan make:provider InertiaSSRServiceProvider
Install the server package:
composer require inertiajs/inertia-laravel
Configuration
Configure SSR in config/inertia.php:
return [
'ssr' => [
'enabled' => true,
'url' => env('INERTIA_SSR_URL', 'http://127.0.0.1:13714'),
'timeout' => 60,
],
'page' => '$page',
'manifest' => public_path('mix-manifest.json'),
];
Set up the SSR server script in package.json:
{
"scripts": {
"build:ssr": "node build/ssr.js",
"ssr": "node build/ssr.js"
}
}
Controllers
Create controllers that return Inertia responses:
class DashboardController extends Controller
{
public function index()
{
return Inertia::render('Dashboard', [
'stats' => [
'users' => User::count(),
'orders' => Order::count(),
'revenue' => Order::sum('total'),
],
'recentOrders' => Order::with('customer')
->latest()
->take(10)
->get(),
]);
}
}
Inertia Pages
Create React/Vue components for your pages:
// resources/js/Pages/Dashboard.jsx
import { usePage } from '@inertiajs/react';
export default function Dashboard() {
const { props } = usePage();
return (
Dashboard
);
}
Partial Reloads
Use partial reloads to fetch only required data:
// Only reload the orders section
const { data } = useForm({
search: '',
});
function handleSearch() {
Inertia.get('/dashboard', {
search: data.search,
only: ['recentOrders'],
});
}
Handle partial props in your component:
// Only revalidate orders on refresh
export default function Dashboard() {
const { recentOrders } = usePage().props;
// Component implementation
}
Summary
Inertia.js with SSR provides the best of both worlds: the developer experience of a single-page application with the SEO and performance benefits of server-side rendering. By following this guide, you can implement SSR in your Laravel applications.
For more information, check out our other tutorials on Laravel Livewire and Laravel Octane.