Using SSR with your Inertia React JS Laravel app

How to make your Inertia and React JS Laravel app utilize server-side rendering and why you should use SSR for your web pages.

What is SSR?

SSR is server-side rendering of webpages and serving it to the client as HTML rather then them rendering it client-side as Javascript.

Naturally React JS is client-side rendered this is its foundation with the virtual DOM updating without reloading the whole page.

Why use SSR?

CSR (client side rendering) can cause web crawlers issues when they come to scan and index your pages, therefore your SEO and page rankings could likely be affected.

In 2 cases for me Google was not able to scan React JS websites that had traditional CSR. The pages would just came up blank because the Google bot was not a traditional “client” browsing the page.

SSR can make your initial page load speed faster than it would be when using CSR. Once the page is loaded however CSR would be faster in doing the virtual DOM manipulations.

Using CSR uses less server processing resources as this is handed off to the client.

React JS Laravel app SSR

Before you adjust your web application to be SSR note that you need to have valid formatted files, that is no unclosed tags and no instances of class= instead of className=. These will throw errors after you have compiled the application files.

In resources/js/ create the file ssr.js

This file should look similar to your app.jsx file, add in the following and edit if need be:

import { createInertiaApp } from '@inertiajs/react'
import createServer from '@inertiajs/react/server'
import ReactDOMServer from 'react-dom/server'

createServer(page =>
    render: ReactDOMServer.renderToString,
    resolve: name => {
      const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
      return pages[`./Pages/${name}.jsx`]
    setup: ({ App, props }) => <App {...props} />,

Add in anything missing from the createInertiaApp() part.

In your vite.config.js file reference this ssr.js file

plugins: [
     input: ['resources/css/app.css', 'resources/js/app.js'],
     ssr: 'resources/js/ssr.js',


Add SSR build into the NPM script (package.json) alongside the client build:

"scripts": {
   "dev": "vite",
   "build": "vite build && vite build --ssr"

Running this command

npm run build

Will build both the client and server side.


The final part is hydration, this is the process of making the now server-side rendered content interactive for the clients.

In app.jsx change createRoot to use hydrateRoot.

Simply run php artisan inertia:start-ssr after you have built the client and server-side bundles with npm run build and you now have SSR.