Skip to content

Head Metadata

Frontend

Head Metadata

Introduction

When someone finds one of your blog posts in a search result or shares a link to it in a chat, the title, description, and preview image they see come from the page's <head>. Because search crawlers and link previews read the first HTML response before any JavaScript runs, those tags need to be rendered on the server. The head package builds a page's head metadata on the server for both views and Inertia pages.

You describe metadata with a head.Head. Your application sets defaults for every page, routes may add metadata that never changes, and handlers merge the metadata that depends on the request before returning a response. For example, this handler sets a post's title and description from its model's fields:

1package posts
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 head.Merge(r, head.Head{Title: post.Title, Description: post.Summary})
18 
19 return web.View("posts.show", post)
20}
1package posts
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 head.Merge(r, head.Head{Title: post.Title, Description: post.Summary})
18 
19 return web.View("posts.show", post)
20}

Rendering the head

New applications already render head metadata in Inertia's root view. If you create a layout for your own views, render the head there as well.

In views

Call head inside your layout's <head> element, right after the tags that are the same on every page, such as charset and viewport:

1<!-- resources/views/layout.html -->
2 
3<head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1">
6 {{head}}
7 {{vite "resources/css/app.css"}}
8</head>
1<!-- resources/views/layout.html -->
2 
3<head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1">
6 {{head}}
7 {{vite "resources/css/app.css"}}
8</head>

Because the head renders along with the view, call head.Merge before your handler returns. Load your stylesheets and scripts after {{head}} with vite.

A view may also set its own title by passing one to head, as in {{head "Users"}}. Laravel renders that title through the title template and uses it in place of any title your handler merged. To learn how a page sets its title from inside a layout, check out the templates guide's section on layouts.

In Inertia pages

Inertia's root view renders the head with {{.Head}} instead of head. Laravel also includes the page's tags in a head prop, so Inertia's client updates the document's head as users navigate between pages. New applications enable this with the serverHead option in resources/js/app.tsx:

1createInertiaApp({
2 serverHead: true,
3 // ...
4});
1createInertiaApp({
2 serverHead: true,
3 // ...
4});

Leave out Inertia's client-side title callback, because Laravel already applies your title template on the server. Set titles, descriptions, and social tags with head.Merge, and keep Inertia's <Head> component for tags the server doesn't render. If both set a <title>, the client replaces the server's title once the page hydrates, while crawlers still read the server's title.

A partial reload, such as router.reload({ only: ['reviews'] }), leaves out the head prop, so the page keeps its existing head tags while its other props refresh.

Setting defaults

Out of the box, Laravel adds your application's name to every page title, such as About · Laravel. Most applications also want a default description, a canonical link, and social tags on every page. To set those defaults, give the Head option in bootstrap/app.go a head.Config:

1package bootstrap
2 
3import (
4 laravel "go.laravel.com"
5 "go.laravel.com/head"
6)
7 
8func Options() laravel.Options {
9 return laravel.Options{
10 // ...
11 Head: head.Config{
12 Defaults: head.Head{
13 Description: "Build something great.",
14 Canonical: head.CurrentURL(),
15 Type: "website",
16 SiteName: "Laravel",
17 TwitterCard: "summary_large_image",
18 },
19 },
20 }
21}
1package bootstrap
2 
3import (
4 laravel "go.laravel.com"
5 "go.laravel.com/head"
6)
7 
8func Options() laravel.Options {
9 return laravel.Options{
10 // ...
11 Head: head.Config{
12 Defaults: head.Head{
13 Description: "Build something great.",
14 Canonical: head.CurrentURL(),
15 Type: "website",
16 SiteName: "Laravel",
17 TwitterCard: "summary_large_image",
18 },
19 },
20 }
21}

head.CurrentURL() renders a <link rel="canonical"> tag for the current URL without its query string, so /posts?utm_source=news and /posts share one canonical URL. To keep specific query parameters, such as the page number of a list, name them, as in head.CurrentURL("page"). To point at a different URL altogether, use head.CanonicalURL("/posts/1").

Titles

Page titles render through a title template, where %s is replaced by the page's title. By default, the template is %s · followed by your application's name, so a page titled About renders About · Laravel. Pages without a title render your application's name alone, and a Title set in the defaults renders as written, without the template.

To customize the template for every page or for a route group, such as an admin area, set TitleTemplate. To render a single page's title as written, merge a template of "%s" along with the title:

1Defaults: head.Head{
2 TitleTemplate: "%s | Laravel News",
3},
1Defaults: head.Head{
2 TitleTemplate: "%s | Laravel News",
3},
1head.Merge(r, head.Head{Title: "Laravel News: Every update in one place", TitleTemplate: "%s"})
1head.Merge(r, head.Head{Title: "Laravel News: Every update in one place", TitleTemplate: "%s"})

Error pages

By default, every error page uses its status's reason phrase as its title, such as Not Found · Laravel. Since search engines shouldn't index error pages, and a 404 page benefits from a clearer description, give head.Config an Errors function. Laravel calls it with the response's status, and it returns the error page's metadata:

1Head: head.Config{
2 Errors: func(status int) head.Head {
3 if status == http.StatusNotFound {
4 return head.Head{
5 Robots: "noindex, follow",
6 Description: "The page you are looking for could not be found.",
7 }
8 }
9 
10 return head.Head{Robots: "noindex, follow"}
11 },
12},
1Head: head.Config{
2 Errors: func(status int) head.Head {
3 if status == http.StatusNotFound {
4 return head.Head{
5 Robots: "noindex, follow",
6 Description: "The page you are looking for could not be found.",
7 }
8 }
9 
10 return head.Head{Robots: "noindex, follow"}
11 },
12},

Error metadata overrides any route or handler metadata and applies to error views and the Inertia error page. If your Render function builds an error page of its own, call head.ErrorPage(r, status) before returning the response so that page gets the same metadata. Error pages leave out the canonical link unless your error metadata sets one.

Metadata for routes

When a page's metadata never changes, such as a contact page's title or a robots rule for an entire admin area, attach a head.Head directly to a route or route group with WithHead in routes/web.go:

1package routes
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/head"
6 "go.laravel.com/routing"
7 
8 "app/handlers/dashboard"
9)
10 
11func Web(route *routing.Router, cfg *config.Config) {
12 route.View("/contact", "contact", nil).
13 WithHead(head.Head{Title: "Contact Us", Description: "Get in touch."})
14 
15 admin := route.Prefix("/admin").WithHead(head.Head{Robots: "noindex, nofollow"})
16 
17 admin.Get("/dashboard", dashboard.Show).WithHead(head.Head{Title: "Dashboard"})
18}
1package routes
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/head"
6 "go.laravel.com/routing"
7 
8 "app/handlers/dashboard"
9)
10 
11func Web(route *routing.Router, cfg *config.Config) {
12 route.View("/contact", "contact", nil).
13 WithHead(head.Head{Title: "Contact Us", Description: "Get in touch."})
14 
15 admin := route.Prefix("/admin").WithHead(head.Head{Robots: "noindex, nofollow"})
16 
17 admin.Get("/dashboard", dashboard.Show).WithHead(head.Head{Title: "Dashboard"})
18}

When nested groups or a route set the same tag, Laravel uses the most specific value: the route's metadata overrides its group's, and an inner group's metadata overrides an outer group's.

Metadata for a page

Most metadata depends on the current request, such as the title and image of a specific post. Call head.Merge in a handler or middleware before the response renders, passing r. A function your handler calls may also merge metadata by passing on the ctx it receives from the handler. You may call head.Merge multiple times during a request, and later calls override earlier ones.

For example, this handler sets a post's Open Graph image from its image_url and image_alt columns, and hides unpublished drafts from search engines:

1package posts
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 head.Merge(r, head.Head{
18 Title: post.Title,
19 Type: "article",
20 Images: []head.Image{
21 {URL: post.ImageURL, Alt: post.ImageAlt, Width: 1200, Height: 630},
22 },
23 })
24 
25 if post.PublishedAt == nil {
26 head.Merge(r, head.Head{Robots: "noindex, nofollow"})
27 }
28 
29 return web.View("posts.show", post)
30}
1package posts
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Show(r *web.Request) *web.Response {
12 post, err := model.FromRoute[models.Post](r, "post")
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 head.Merge(r, head.Head{
18 Title: post.Title,
19 Type: "article",
20 Images: []head.Image{
21 {URL: post.ImageURL, Alt: post.ImageAlt, Width: 1200, Height: 630},
22 },
23 })
24 
25 if post.PublishedAt == nil {
26 head.Merge(r, head.Head{Robots: "noindex, nofollow"})
27 }
28 
29 return web.View("posts.show", post)
30}

If several handlers describe the same model, you may give the model a method that returns its head.Head, next to the model's fields, and pass the method's result to head.Merge in your handler:

1func (p Post) Head() head.Head {
2 return head.Head{Title: p.Title, Description: p.Summary}
3}
1func (p Post) Head() head.Head {
2 return head.Head{Title: p.Title, Description: p.Summary}
3}
1head.Merge(r, post.Head())
1head.Merge(r, post.Head())

How layers combine

Laravel merges metadata from six layers, from lowest priority to highest:

  1. Your application's name, used as the fallback title.
  2. The defaults in head.Config, set in bootstrap/app.go.
  3. Metadata attached to route groups, followed by metadata attached directly to the route.
  4. Each head.Merge call made during the request, in the order called.
  5. The title a view passes to head, as in {{head "Users"}}.
  6. On error pages, the status's reason phrase as the title, followed by the metadata from the Errors function.

For each field, such as Title or Description, the highest layer that sets it takes precedence, while lower layers keep their other fields. So a route's description stays in place when a handler only sets the title. Meta, Links, ThemeColors, Icons, Preconnect, Preloads, and Feeds combine across layers, and a higher layer replaces matching entries such as the same Meta name, the same ThemeColor media query, or a link with the same Rel and Hreflang. A page's Images replace those from the lower layers, so a post's photo isn't rendered alongside your site's default social image.

Open Graph and Twitter

When someone shares a link on social media or in a chat app, the link preview reads the page's Open Graph and Twitter Card tags. With the defaults set earlier, calling head.Merge in the /posts/1 handler:

1head.Merge(r, head.Head{
2 Title: "Introducing head metadata",
3 Description: "Titles and social tags for every page.",
4 Images: []head.Image{{URL: "/images/social.jpg", Alt: "Introducing head metadata"}},
5})
1head.Merge(r, head.Head{
2 Title: "Introducing head metadata",
3 Description: "Titles and social tags for every page.",
4 Images: []head.Image{{URL: "/images/social.jpg", Alt: "Introducing head metadata"}},
5})

produces the following tags in the document's <head>:

1<title>Introducing head metadata · Laravel</title>
2<meta name="description" content="Titles and social tags for every page.">
3<link rel="canonical" href="https://example.com/posts/1">
4<meta property="og:type" content="website">
5<meta property="og:site_name" content="Laravel">
6<meta property="og:title" content="Introducing head metadata · Laravel">
7<meta property="og:description" content="Titles and social tags for every page.">
8<meta property="og:image" content="https://example.com/images/social.jpg">
9<meta property="og:image:alt" content="Introducing head metadata">
10<meta name="twitter:card" content="summary_large_image">
11<meta name="twitter:title" content="Introducing head metadata · Laravel">
12<meta name="twitter:description" content="Titles and social tags for every page.">
13<meta name="twitter:image" content="https://example.com/images/social.jpg">
14<meta name="twitter:image:alt" content="Introducing head metadata">
1<title>Introducing head metadata · Laravel</title>
2<meta name="description" content="Titles and social tags for every page.">
3<link rel="canonical" href="https://example.com/posts/1">
4<meta property="og:type" content="website">
5<meta property="og:site_name" content="Laravel">
6<meta property="og:title" content="Introducing head metadata · Laravel">
7<meta property="og:description" content="Titles and social tags for every page.">
8<meta property="og:image" content="https://example.com/images/social.jpg">
9<meta property="og:image:alt" content="Introducing head metadata">
10<meta name="twitter:card" content="summary_large_image">
11<meta name="twitter:title" content="Introducing head metadata · Laravel">
12<meta name="twitter:description" content="Titles and social tags for every page.">
13<meta name="twitter:image" content="https://example.com/images/social.jpg">
14<meta name="twitter:image:alt" content="Introducing head metadata">

Once a page has any Open Graph field, such as Type, og:title and og:description fall back to the page's title and description. Similarly, once a page has a TwitterCard, the Twitter tags fall back to the Open Graph values. To give social sites different text, set the tag in Meta. A Meta entry always takes precedence over these fallbacks, and the Twitter tags follow an og:title or og:description you set:

1head.Merge(r, head.Head{Meta: map[string]string{"og:title": "Read this first"}})
1head.Merge(r, head.Head{Meta: map[string]string{"og:title": "Read this first"}})

Relative image paths such as /images/social.jpg are expanded to absolute URLs, since social crawlers require full URLs.

Icons, hints, and other tags

Browsers also read <head> for favicons, theme colors, resource preloads, and RSS or Atom feeds. Most applications set these once in Head.Defaults inside bootstrap/app.go:

1Head: head.Config{
2 Defaults: head.Head{
3 ThemeColors: []head.ThemeColor{
4 {Color: "#ffffff"},
5 {Color: "#111827", Media: head.Dark},
6 },
7 Icons: []head.Icon{
8 {Href: "/favicon.svg", Type: "image/svg+xml"},
9 head.AppleTouchIcon("/apple-touch-icon.png", "180x180"),
10 },
11 Manifest: "/site.webmanifest",
12 Preconnect: []string{"https://fonts.bunny.net"},
13 Preloads: []head.Preload{
14 {Href: "/fonts/inter.woff2", As: "font", Type: "font/woff2"},
15 },
16 Feeds: []head.Feed{
17 head.Atom("/feed.atom", "Laravel Atom"),
18 },
19 },
20},
1Head: head.Config{
2 Defaults: head.Head{
3 ThemeColors: []head.ThemeColor{
4 {Color: "#ffffff"},
5 {Color: "#111827", Media: head.Dark},
6 },
7 Icons: []head.Icon{
8 {Href: "/favicon.svg", Type: "image/svg+xml"},
9 head.AppleTouchIcon("/apple-touch-icon.png", "180x180"),
10 },
11 Manifest: "/site.webmanifest",
12 Preconnect: []string{"https://fonts.bunny.net"},
13 Preloads: []head.Preload{
14 {Href: "/fonts/inter.woff2", As: "font", Type: "font/woff2"},
15 },
16 Feeds: []head.Feed{
17 head.Atom("/feed.atom", "Laravel Atom"),
18 },
19 },
20},

For Preloads with As: "font", Laravel adds a crossorigin attribute automatically unless you set CrossOrigin explicitly, because browsers always fetch preloaded fonts in CORS mode. For RSS feeds, use head.RSS in place of head.Atom.

For any <meta> tag without a dedicated field, such as an article's author, add the tag to Meta by name. Open Graph names, such as og:locale and article:author, render with a property attribute, and other names render with a name attribute:

1head.Merge(r, head.Head{Meta: map[string]string{
2 "article:author": post.Author,
3 "twitter:site": "@laravelphp",
4}})
1head.Merge(r, head.Head{Meta: map[string]string{
2 "article:author": post.Author,
3 "twitter:site": "@laravelphp",
4}})

For any other <link> tag, such as a link to the page in another language or an OpenSearch description, add entries to Links:

1head.Merge(r, head.Head{Links: []head.Link{
2 {Rel: "alternate", Href: "/fr/posts", Hreflang: "fr"},
3 {Rel: "search", Href: "/opensearch.xml", Type: "application/opensearchdescription+xml", Title: "Search"},
4}})
1head.Merge(r, head.Head{Links: []head.Link{
2 {Rel: "alternate", Href: "/fr/posts", Hreflang: "fr"},
3 {Rel: "search", Href: "/opensearch.xml", Type: "application/opensearchdescription+xml", Title: "Search"},
4}})

On paginated pages, pass your paginator to head.Paginated. It keeps the paginator's page parameter (such as page or cursor) in the canonical URL and adds <link rel="prev"> and <link rel="next"> tags when neighboring pages exist:

1package posts
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Index(r *web.Request) *web.Response {
12 posts, err := model.Query[models.Post]().Latest("published_at").Paginate(r, r.Page(15))
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 head.Merge(r, head.Paginated(posts))
18 
19 return web.View("posts.index", posts)
20}
1package posts
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/model"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func Index(r *web.Request) *web.Response {
12 posts, err := model.Query[models.Post]().Latest("published_at").Paginate(r, r.Page(15))
13 if err != nil {
14 return web.Fail(err)
15 }
16 
17 head.Merge(r, head.Paginated(posts))
18 
19 return web.View("posts.index", posts)
20}

Structured data

Search engines read JSON-LD structured data to display rich results, such as a product's price and stock status next to its search listing. Add the data to a page's Schemas, and each schema renders as a <script type="application/ld+json"> tag. The head/jsonld package includes types for Article, BlogPosting, Product, Offer, Brand, Breadcrumbs, FAQ, Organization, Person, WebPage, and WebSite:

1package products
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/head/jsonld"
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12func Show(r *web.Request) *web.Response {
13 product, err := model.FromRoute[models.Product](r, "product")
14 if err != nil {
15 return web.Fail(err)
16 }
17 
18 head.Merge(r, head.Head{
19 Title: product.Name,
20 Schemas: []head.Schema{
21 jsonld.Product{
22 Name: product.Name,
23 Offers: &jsonld.Offer{
24 Price: product.Price,
25 Currency: "USD",
26 Availability: jsonld.InStock,
27 },
28 },
29 jsonld.Breadcrumbs{
30 {Name: "Home", URL: "https://example.com"},
31 {Name: "Shop", URL: "https://example.com/shop"},
32 },
33 },
34 })
35 
36 return web.View("products.show", product)
37}
1package products
2 
3import (
4 "go.laravel.com/head"
5 "go.laravel.com/head/jsonld"
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12func Show(r *web.Request) *web.Response {
13 product, err := model.FromRoute[models.Product](r, "product")
14 if err != nil {
15 return web.Fail(err)
16 }
17 
18 head.Merge(r, head.Head{
19 Title: product.Name,
20 Schemas: []head.Schema{
21 jsonld.Product{
22 Name: product.Name,
23 Offers: &jsonld.Offer{
24 Price: product.Price,
25 Currency: "USD",
26 Availability: jsonld.InStock,
27 },
28 },
29 jsonld.Breadcrumbs{
30 {Name: "Home", URL: "https://example.com"},
31 {Name: "Shop", URL: "https://example.com/shop"},
32 },
33 },
34 })
35 
36 return web.View("products.show", product)
37}

Unlike other fields, a layer's schemas add to the lower layers' schemas, so you may describe your site once with a jsonld.WebSite in the defaults while each page adds its own.

For any other schema.org type, use a jsonld.Thing with the type under @type, such as jsonld.Thing{"@type": "Recipe", "name": "Pancakes"}. If you reuse a custom schema type across your application, give a struct of your own a SchemaType method:

1type JobPosting struct {
2 Title string `json:"title"`
3 Location string `json:"jobLocation,omitzero"`
4}
5 
6func (JobPosting) SchemaType() string { return "JobPosting" }
1type JobPosting struct {
2 Title string `json:"title"`
3 Location string `json:"jobLocation,omitzero"`
4}
5 
6func (JobPosting) SchemaType() string { return "JobPosting" }

Omit empty fields with omitzero, as Location does, rather than sending empty strings or nil. A schema containing an empty value fails the page with a 500, and in debug mode the error page names the empty value's path.

Testing the head

In your HTTP tests, the head assertions inspect either the <head> of an HTML response or the head prop of an Inertia page, so the same assertions work for views and Inertia pages:

1package feature_test
2 
3import (
4 "testing"
5 
6 "app/tests"
7)
8 
9func TestPostPagesHaveSocialTags(t *testing.T) {
10 client := tests.New(t)
11 
12 client.Get("/posts/1").AssertOK().
13 AssertTitle("Hello World · Laravel").
14 AssertMeta("og:title", "Hello World · Laravel").
15 AssertLink("canonical", "http://example.com/posts/1").
16 AssertMetaMissing("robots")
17}
1package feature_test
2 
3import (
4 "testing"
5 
6 "app/tests"
7)
8 
9func TestPostPagesHaveSocialTags(t *testing.T) {
10 client := tests.New(t)
11 
12 client.Get("/posts/1").AssertOK().
13 AssertTitle("Hello World · Laravel").
14 AssertMeta("og:title", "Hello World · Laravel").
15 AssertLink("canonical", "http://example.com/posts/1").
16 AssertMetaMissing("robots")
17}
Assertion What it checks
AssertTitle(text) That the head contains a single <title> with the given text.
AssertMeta(name, content) That a <meta> tag with the given name or property has the expected content.
AssertMetaMissing(name) That the head has no <meta> tag with the given name or property, such as robots.
AssertLink(rel, href) That a <link> tag has the given rel and URL.
AssertLinkMissing(rel) That the head has no <link> tag with the given rel, such as canonical on an error page.
AssertSchema(type) That a JSON-LD schema has the given @type, such as Product.

To verify that a partial reload leaves out the head prop, reload the page and assert AssertPropMissing("head"):

1func TestReviewsReloadWithoutTheHead(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Get("/products/1").ReloadOnly("reviews").AssertPropMissing("head")
5}
1func TestReviewsReloadWithoutTheHead(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Get("/products/1").ReloadOnly("reviews").AssertPropMissing("head")
5}