Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route is not defined, laravel breeze inertia react SSR

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)
like image 714
parth Avatar asked Nov 17 '25 13:11

parth


1 Answers

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

like image 174
bee bee Avatar answered Nov 20 '25 02:11

bee bee