We usually struggle to make our single page applications SEO friendly as they render in client side.
Meta tags and other SEO friendly information should be render from server side in order to make the application SEO friendly.
In laravel with inertia we render one single view for every route.
If we want to render meta tags from server side, we have to pass those information to that view.
We can use a simple class to achieve this.
in app\Meta.php (You can put this class anywhere you want).
<?phpnamespaceApp;classMeta{protectedstatic$meta=[];publicstaticfunctionaddMeta($name,$content){static::$meta[$name]=$content;}publicstaticfunctionrender(){$html='';foreach(static::$metaas$name=>$content){$html.='<meta name="'.$name.'" content="'.$content.'" />'.PHP_EOL;}return$html;}}
Now in the controller add meta or code snippet as you want.
useApp\Meta;publicfunctionindex(){Meta::addMeta('title','Dashboard');Meta::addMeta('description','My awesome site .....');returnInertia::render('Dashboard');}
To add a meta tag, calladdMeta
method ofMeta
class with name as first parameter and content as second parameter.
You can add as many meta tags as you want.
Now in view we need to render those meta tags.
To render those, just callrender
method ofMeta
class.
<metacharset="utf-8"><metaname="viewport"content="width=device-width, initial-scale=1">{!! \App\Meta::render() !!}
Now if we check source, we'll find our meta tags and snippets.
Note that if you want to use this approach with laravel octane, this will lead to unexpected result.
We have to clean it up in every request.
In order to claen up, add cleanup method inMeta
class.
publicstaticfunctioncleanup(){static::$meta=[];}
Now we can cleanup by listeningRequestReceived
event of laravel octane.
InEventServiceProvider
useApp\Meta;useIlluminate\Support\Facades\Event;useLaravel\Octane\Events\RequestReceived;publicfunctionboot(){Event::listen(function(RequestReceived$_){Meta::cleanup();});}
This is just a simple idea on how we can make inertia SEO friendly.
Have Fun 🎉 !!!
Top comments(5)

- LocationBuenos Aires, Argentina
- WorkDeveloper: fullstack, backend, frontend... it depends on the project.
- Joined
Interesting approach, but doesn't Inertia have SSR features? Are they enough to get a good SEO?

SSR is good for SEO. When I've written the article, SSR in inertia was not available.
Now SSR is available. You can use SSR for SEO.
For further actions, you may consider blocking this person and/orreporting abuse