Vlad Osmianski
Vlad Osmianski's Blog

Follow

Vlad Osmianski's Blog

Follow

Configuring Server-Side Rendering In A Laravel + Vue + Inertia Project

Vlad Osmianski's photo
Vlad Osmianski
·Oct 4, 2022·

2 min read

My last article provided a detailed step-by-step guide about adding Vue.js and Inertia.js to a Laravel project.

All is good, but here a one little problem. It's renders pages using JavaScript, and it may be bad for SEO. This article aims to fix this.

The solution is to render pages on the server and here is how to configure it:

  1. Install Node modules required by server-side rendering (SSR):

     npm install --dev @vue/server-renderer @inertiajs/server
    
  2. Create a resources/js/ssr.js file, that is going to be similar to app.js file, with the exception that it's not going to run in the browser, but rather in Node.js:

     import '../css/app.css';
    
     import { createSSRApp, h } from 'vue'
     import { renderToString } from 'vue/server-renderer'
     import { createInertiaApp } from '@inertiajs/inertia-vue3'
     import createServer from '@inertiajs/server'
     import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
    
     createServer((page) => createInertiaApp({
         page,
         render: renderToString,
         resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`,
             import.meta.glob('./Pages/**/*.vue')),
         setup: ({ app, props, plugin }) => {
             return createSSRApp({
                 render: () => h(app, props)
             }).use(plugin)
         },
     }))
    
  3. Add SSR configuration to vite.config.js:

     ...
     export default defineConfig({
         plugins: [
             laravel({
                 ...
                 ssr: 'resources/js/ssr.js',
             }),
                     ...
         ],
         ssr: {
             // fix, see https://github.com/inertiajs/server/issues/10#issuecomment-1208751934
             noExternal: ['@inertiajs/server'],
         },
     });
    
  4. Add instructions to build SSR version of your app to the package.json:

     {
             ...
         "scripts": {
             ...
             "build": "vite build && vite build --ssr"
         },
         ...
     }
    
  5. Create config/inertia.php file by running the following command:

     php artisan vendor:publish --provider="Inertia\ServiceProvider"
    
  6. Enable SSR in the config/inertia.php:

     <?php
    
     return [
             ...
         'ssr' => [
             'enabled' => true,
                     ...
         ],
             ...
     ];
    
  7. Instead of npm run dev, run the following:

     npm run build
     node bootstrap/ssr/ssr.mjs
    
  8. Refresh the page and check the page source to see that the main application <div> is no longer empty.

 
Share this