I am using Reactjs with Laravel 7. Everything works fine except the dynamic meta tags on each page of my website was not updating when API request is sent in the backend. I did use the react-helmet package but it did not update the meta tags. I also used the Laravel butschster/LaravelMetaTags package, which also did not solve the issue.
I decided to use the spatie/laravel-server-side-rendering and add SSR to my application. Here is the implementation I have done so far.
index.blade.php
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<meta>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ config('custom.title') }}</title>
<meta name="description" content="{{ config('custom.description') }}"/>
{{--
default meta tags, it should be updated with API request
--}}
<meta property="og:title" content="{{ config('custom.title') }}"/>
<meta property="og:description" content="{{ config('custom.description') }}"/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="{{url()->current()}}"/>
<meta property="og:image" content=""/>
<link rel="canonical" href="{{url()->current()}}"/>
</head>
<body>
{!! ssr('build/js/server.js')
->fallback('<div id="frontend"></div>')
->render()!!}
<script src="{{ asset(mix('build/js/client.js')) }}"></script>
<script src="{{ asset(mix('build/js/server.js')) }}"></script>
</body>
</html>
server.js
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import FrontApp from './FrontApp';
const html = ReactDOMServer.renderToString(
<div id="frontend">
<h1>Testing</h1>//this is not displayed at all.
</div>
);
dispatch(html);//this gives error.
client.js
import React from 'react';
import {render} from 'react-dom';
import FrontApp from './App';//this is the main App.
if (document.getElementById('frontend')) {
render(<App/>, document.getElementById('frontend'));
}
Let me describe a bit more about the app:
It is a SPA and the index.blade.php is loaded only for the first time. The rest of the pages are using HTTP requests. What I want is to update the meta tags when the HTTP request is sent from client to server.
Current Error:
I get a console error: Uncaught ReferenceError: dispatch is not defined when loading my app for the first time. It seems the SSR server is not working at all.
For now, I don't know why the dispatch method is not working and it uses the fallback div (i.e. ->fallback('<div id="frontend"></div>')).
Please help me with this issue and the dynamic meta tags. Any alternative solution is also welcomed. Thanks.