spatie/server-side-rendering
Render JavaScript server-side from PHP with minimal setup. Works with any SSR-capable framework, supports V8Js or a Node-based engine, and lets you execute an entry script to return rendered HTML—ideal for adding SSR to existing PHP apps.
Start by installing the package via Composer:
composer require spatie/server-side-rendering
Then publish the config file:
php artisan vendor:publish --tag="server-side-rendering-config"
The default config (config/ssr.php) points to storage/app/ssr/index.js as the entry point. Create that file and implement a basic renderer (e.g., using React or Vue). For example:
// storage/app/ssr/index.js
const Vue = require('vue');
const app = new Vue({
render: h => h({ template: '<div>Hello, {{ name }}!</div>', props: ['name'] }),
props: ['name'],
});
module.exports = (context) => app.$mount().toString();
In a Laravel controller or view, render like:
use Spatie\Ssr\Facades\Ssr;
return view('welcome', [
'html' => Ssr::render('index.js', ['name' => 'World']),
]);
Finally, ensure Node.js is installed and accessible in your environment—this package executes the JS file via CLI.
class VueRenderer
{
public static function render(string $component, array $props = []): string
{
return Ssr::render('index.js', [
'component' => $component,
'props' => $props,
]);
}
}
$cacheKey = "ssr:{$component}:" . md5(serialize($props));
$html = Cache::remember($cacheKey, now()->addDay(), fn() => Ssr::render(...));
@ssr directive or helper:
// In AppServiceProvider::boot()
Blade::directive('ssr', fn ($expression) => "<?= \Spatie\Ssr\Facades\Ssr::render({$expression}) ?>");
config/ssr.php, use environment-specific settings (e.g., execCommand() vs http://ssr-container:3000/render) to support Docker or remote rendering in production.Node not installed, script crash) throw Spatie\Ssr\Exceptions\RendererException. Wrap calls in try/catch, and fallback to client-side hydration (v-cloak) or static fallback HTML.json_encode($data) in JS context).execCommand() (e.g., php artisan path:resolve(storage_path('app/ssr/index.js'))) to avoid environment-specific bugs.spatie/server-side-rendering’s HTTP renderer or your own Fastify/Express service) and call it over HTTP.Ssr::render() in unit tests; use feature tests with real Node to validate your renderer script end-to-end.execCommand to ['node', '--inspect-brk', $script] and attach your IDE debugger, or log $command in the Ssr facade to inspect the exact CLI invocation.How can I help you explore Laravel packages today?