0

I am trying to use SSR inertiajs with react, in laravel.

Version details:

Php: 8.1.2
Laravel: 8.82.0
Breeze: 1.7.1
Inertiajs: 0.11.0
Npm: 8.1.2

/resources/js/ssr.js

createServer((page) => createInertiaApp({
  page,
  render: ReactDOMServer.renderToString,
  resolve: name => require(`./Pages/${name}`),
  setup: ({ App, props }) => <App {...props} />,
}))

/webpack.ssr.mix.js

mix
  .options({ manifest: false })
  .js('resources/js/ssr.js', 'public/js')
  .react()
  .alias({ '@': path.resolve('resources/js') })
  .webpackConfig({
    target: 'node',
    externals: [nodeExternals()],
  })

/resources/views/app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        ...
        <link rel="stylesheet" href="{{ mix('css/app.css') }}">
        @routes
        <script src="{{ mix('js/app.js') }}" defer></script>
        @inertiaHead
    </head>
    <body class="font-sans antialiased">
        @inertia

        ...
    </body>
</html>

Error:

ReferenceError: route is not defined
at Welcome (/public/js/ssr.js:1413:19)
parth
  • 1,803
  • 2
  • 19
  • 27

3 Answers3

0

Have you tried this? It was in the Routing - Inertia.

app.config.globalProperties.$route = route

0

First you need to get ziggy-js

npm install ziggy-js

Then run

php artisan ziggy:generate

Which should create a ziggy.js file in the resources/js directory. After modify your ssr.js to

import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { createInertiaApp } from '@inertiajs/inertia-react'
import createServer from '@inertiajs/server'
import route from "ziggy-js";
import { Ziggy } from '@/ziggy'


createServer((page) => createInertiaApp({
    page,
    render: ReactDOMServer.renderToString,
    resolve: name => require(`./Pages/${name}`),
    setup: ({ App, props }) => {

        // Set global function route
        global.route = (name, params, absolute, config = Ziggy) => route(name, params, absolute, config);

        return <App {...props} />
    },
}))

Solution by JefteCaro

More solutions in case you'd like to read more

bee bee
  • 1
  • 1
0

replace

<script src="{{ mix('js/app.js') }}" defer></script>

with

<script src="{{ mix('js/ssr.js') }}" defer></script>

in /resources/views/app.blade.php

Minus
  • 11
  • 1
  • 4