To set up Server-Side Rendering (SSR) with Laravel 11, VueJS 3, and Vite, you need to follow a few steps. The Laravel documentation provides a good starting point, but let's go into more detail, especially about the ssr.js file.
Step-by-Step Guide
-
Install Dependencies: Ensure you have the necessary dependencies installed. You need
vite,@vitejs/plugin-vue, and@vitejs/plugin-vue-jsx.npm install vite @vitejs/plugin-vue @vitejs/plugin-vue-jsx -
Configure Vite: Create or update your
vite.config.jsfile to include the Vue plugin and SSR settings.import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import vueJsx from '@vitejs/plugin-vue-jsx'; export default defineConfig({ plugins: [vue(), vueJsx()], ssr: { noExternal: ['vue', '@vue/server-renderer'] } }); -
Create
ssr.js: This file is responsible for rendering your Vue components on the server side. Here is a basic example of whatssr.jsmight look like:import { createSSRApp } from 'vue'; import { renderToString } from '@vue/server-renderer'; import App from './src/App.vue'; export async function render(url, manifest) { const app = createSSRApp(App); // You can add any additional setup here, like Vue Router or Vuex const appHtml = await renderToString(app); return { appHtml }; } -
Update Laravel Routes: In your Laravel routes file (e.g.,
web.php), you need to set up a route that will handle SSR.use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\App; Route::get('/{any}', function () { $ssr = App::make('vite.ssr'); $manifest = json_decode(File::get(public_path('build/manifest.json')), true); $result = $ssr->render('/', $manifest); return view('app', [ 'ssr' => $result['appHtml'] ]); })->where('any', '.*'); -
Create a Blade Template: Create a Blade template (e.g.,
resources/views/app.blade.php) to serve the SSR content.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My SSR App</title> @vite('resources/js/app.js') </head> <body> <div id="app">{!! $ssr !!}</div> </body> </html> -
Run Vite in SSR Mode: Finally, you need to run Vite in SSR mode. You can add a script to your
package.jsonto make this easier."scripts": { "dev": "vite", "build": "vite build", "ssr": "vite build --ssr" }Run the SSR build with:
npm run ssr
Summary
By following these steps, you should be able to set up SSR for your Laravel 11 application using VueJS 3 and Vite. The key part is the ssr.js file, which handles the server-side rendering of your Vue components. Make sure to adjust the configurations and routes according to your application's needs.