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).
<?php
namespace App;
class Meta
{
protected static $meta = [];
public static function addMeta($name, $content)
{
static::$meta[$name] = $content;
}
public static function render()
{
$html = '';
foreach (static::$meta as $name => $content) {
$html .= '<meta name="'.$name.'" content="'.$content.'" />'.PHP_EOL;
}
return $html;
}
}
Now in the controller add meta or code snippet as you want.
use App\Meta;
public function index() {
Meta::addMeta('title', 'Dashboard');
Meta::addMeta('description', 'My awesome site .....');
return Inertia::render('Dashboard');
}
To add a meta tag, call addMeta
method of Meta
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 call render
method of Meta
class.
<meta charset="utf-8">
<meta name="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 in Meta
class.
public static function cleanup()
{
static::$meta = [];
}
Now we can cleanup by listening RequestReceived
event of laravel octane.
In EventServiceProvider
use App\Meta;
use Illuminate\Support\Facades\Event;
use Laravel\Octane\Events\RequestReceived;
public function boot()
{
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)
Really awesome lets rock with inertia,vue seo friendly
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.
Thanks for your kindly reply!
thank you really that was so helpful