Head Metadata
- Introduction
- Rendering the head
- Setting defaults
- Metadata for routes
- Metadata for a page
- Open Graph and Twitter
- Icons, hints, and other tags
- Structured data
- Testing the head
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:
package posts
import (
"go.laravel.com/head"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Show(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
head.Merge(r, head.Head{Title: post.Title, Description: post.Summary})
return web.View("posts.show", post)
}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:
<!-- resources/views/layout.html -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{head}}
{{vite "resources/css/app.css"}}
</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:
createInertiaApp({
serverHead: true,
// ...
});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:
package bootstrap
import (
laravel "go.laravel.com"
"go.laravel.com/head"
)
func Options() laravel.Options {
return laravel.Options{
// ...
Head: head.Config{
Defaults: head.Head{
Description: "Build something great.",
Canonical: head.CurrentURL(),
Type: "website",
SiteName: "Laravel",
TwitterCard: "summary_large_image",
},
},
}
}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:
Defaults: head.Head{
TitleTemplate: "%s | Laravel News",
},head.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:
Head: head.Config{
Errors: func(status int) head.Head {
if status == http.StatusNotFound {
return head.Head{
Robots: "noindex, follow",
Description: "The page you are looking for could not be found.",
}
}
return head.Head{Robots: "noindex, follow"}
},
},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:
package routes
import (
"go.laravel.com/config"
"go.laravel.com/head"
"go.laravel.com/routing"
"app/handlers/dashboard"
)
func Web(route *routing.Router, cfg *config.Config) {
route.View("/contact", "contact", nil).
WithHead(head.Head{Title: "Contact Us", Description: "Get in touch."})
admin := route.Prefix("/admin").WithHead(head.Head{Robots: "noindex, nofollow"})
admin.Get("/dashboard", dashboard.Show).WithHead(head.Head{Title: "Dashboard"})
}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:
package posts
import (
"go.laravel.com/head"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Show(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
head.Merge(r, head.Head{
Title: post.Title,
Type: "article",
Images: []head.Image{
{URL: post.ImageURL, Alt: post.ImageAlt, Width: 1200, Height: 630},
},
})
if post.PublishedAt == nil {
head.Merge(r, head.Head{Robots: "noindex, nofollow"})
}
return web.View("posts.show", post)
}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:
func (p Post) Head() head.Head {
return head.Head{Title: p.Title, Description: p.Summary}
}head.Merge(r, post.Head())How layers combine
Laravel merges metadata from six layers, from lowest priority to highest:
- Your application's name, used as the fallback title.
- The defaults in
head.Config, set inbootstrap/app.go. - Metadata attached to route groups, followed by metadata attached directly to the route.
- Each
head.Mergecall made during the request, in the order called. - The title a view passes to
head, as in{{head "Users"}}. - On error pages, the status's reason phrase as the title, followed by the metadata from the
Errorsfunction.
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:
head.Merge(r, head.Head{
Title: "Introducing head metadata",
Description: "Titles and social tags for every page.",
Images: []head.Image{{URL: "/images/social.jpg", Alt: "Introducing head metadata"}},
})produces the following tags in the document's <head>:
<title>Introducing head metadata · Laravel</title>
<meta name="description" content="Titles and social tags for every page.">
<link rel="canonical" href="https://example.com/posts/1">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Laravel">
<meta property="og:title" content="Introducing head metadata · Laravel">
<meta property="og:description" content="Titles and social tags for every page.">
<meta property="og:image" content="https://example.com/images/social.jpg">
<meta property="og:image:alt" content="Introducing head metadata">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Introducing head metadata · Laravel">
<meta name="twitter:description" content="Titles and social tags for every page.">
<meta name="twitter:image" content="https://example.com/images/social.jpg">
<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:
head.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:
Head: head.Config{
Defaults: head.Head{
ThemeColors: []head.ThemeColor{
{Color: "#ffffff"},
{Color: "#111827", Media: head.Dark},
},
Icons: []head.Icon{
{Href: "/favicon.svg", Type: "image/svg+xml"},
head.AppleTouchIcon("/apple-touch-icon.png", "180x180"),
},
Manifest: "/site.webmanifest",
Preconnect: []string{"https://fonts.bunny.net"},
Preloads: []head.Preload{
{Href: "/fonts/inter.woff2", As: "font", Type: "font/woff2"},
},
Feeds: []head.Feed{
head.Atom("/feed.atom", "Laravel Atom"),
},
},
},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:
head.Merge(r, head.Head{Meta: map[string]string{
"article:author": post.Author,
"twitter:site": "@laravelphp",
}})For any other <link> tag, such as a link to the page in another language or an OpenSearch description, add entries to Links:
head.Merge(r, head.Head{Links: []head.Link{
{Rel: "alternate", Href: "/fr/posts", Hreflang: "fr"},
{Rel: "search", Href: "/opensearch.xml", Type: "application/opensearchdescription+xml", Title: "Search"},
}})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:
package posts
import (
"go.laravel.com/head"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Index(r *web.Request) *web.Response {
posts, err := model.Query[models.Post]().Latest("published_at").Paginate(r, r.Page(15))
if err != nil {
return web.Fail(err)
}
head.Merge(r, head.Paginated(posts))
return web.View("posts.index", posts)
}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:
package products
import (
"go.laravel.com/head"
"go.laravel.com/head/jsonld"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Show(r *web.Request) *web.Response {
product, err := model.FromRoute[models.Product](r, "product")
if err != nil {
return web.Fail(err)
}
head.Merge(r, head.Head{
Title: product.Name,
Schemas: []head.Schema{
jsonld.Product{
Name: product.Name,
Offers: &jsonld.Offer{
Price: product.Price,
Currency: "USD",
Availability: jsonld.InStock,
},
},
jsonld.Breadcrumbs{
{Name: "Home", URL: "https://example.com"},
{Name: "Shop", URL: "https://example.com/shop"},
},
},
})
return web.View("products.show", product)
}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:
type JobPosting struct {
Title string `json:"title"`
Location string `json:"jobLocation,omitzero"`
}
func (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:
package feature_test
import (
"testing"
"app/tests"
)
func TestPostPagesHaveSocialTags(t *testing.T) {
client := tests.New(t)
client.Get("/posts/1").AssertOK().
AssertTitle("Hello World · Laravel").
AssertMeta("og:title", "Hello World · Laravel").
AssertLink("canonical", "http://example.com/posts/1").
AssertMetaMissing("robots")
}| 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"):
func TestReviewsReloadWithoutTheHead(t *testing.T) {
client := tests.New(t)
client.Get("/products/1").ReloadOnly("reviews").AssertPropMissing("head")
}