Neel Bhalodiya
Posted on October 14, 2024
Before starting, ensure you're using the latest version of Inertia.js. If not, you can upgrade by following the Upgrade Guide.
Step 1: Install Required Packages
For React:
- You don't need to install any specific package for SSR in React.
For Laravel:
- You need to install the SSR package for Laravel:
composer require inertiajs/inertia-laravel
Step 2: Create an SSR File
Create an ssr.jsx or ssr.js file inside the resources/js/ directory. The full path should look like this: resources/js/ssr.js. You can use the following command to create the file:
touch resources/js/ssr.js
After creating the file, you need to define the resolve and setup functions for your ssr.jsx or ssr.js.
For the exmple this shown you can check here:
Step 3: Update vite.config.js
- Now, update your vite.config.js file by adding the SSR property. In the laravel function (after the input function), add the following line
ssr:
'resources/js/ssr.js'
Step 4: Update package.json
- Next, modify your package.json file to include both a normal build and an SSR build. Replace the existing build script with:
"build": "vite build && vite build - ssr"
Now, run the following build command in your terminal:
npm run build
After the build completes, start the SSR service with the following Artisan command:
php artisan inertia:start-ssr
Step 5: Update app.jsx
- In your app.jsx, replace createRoot with hydrateRoot to enable SSR.
Note: Potential Issues with SSR
- After completing all the steps, you may encounter errors with some React components. This is because certain npm libraries do not support SSR. For example, I faced issues with the lightgallery npm package as it didn't fully support SSR. In such cases, you can conditionally import libraries that don't work with SSR.
- With these steps, you should have a fully functional SSR setup for Inertia.js with React using Vite as your bundler.
Posted on October 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.