LaraflareDocsFrameworkPackagesReleases13.x

Docs / Packages / Head

Head

Introduction

Head provides a fluent API for managing your application's document <head> element, including title and meta tags, Open Graph metadata, canonical URLs, robots directives, performance hints, and structured data.

Installation

Head ships inside laraflare's framework package and is imported from @laraflare/framework/head. Register its service provider in bootstrap/providers.ts:

import { HeadServiceProvider } from '@laraflare/framework/head';

import { AppServiceProvider } from '../app/Providers/AppServiceProvider';
import { FortifyServiceProvider } from '../app/Providers/FortifyServiceProvider';

export const providers = [AppServiceProvider, FortifyServiceProvider, HeadServiceProvider];

Quickstart

Register site-wide defaults in a service provider:

import { Head, HeadBuilder } from '@laraflare/framework/head';

Head.defaults((head: HeadBuilder) => head
    .title('laraflare', { suffix: ' - laraflare' })
    .description('Build something great.'));

Set page-specific metadata at runtime:

Head.title(post.title)
    .description(post.description);

Render the resolved tags in your document's <head>:

const tags = Head.toHtml();

Resolution Precedence

Page metadata resolves from five layers, listed from lowest to highest priority:

  1. Page defaults
  2. Route group metadata
  3. Route metadata
  4. Runtime metadata
  5. Error metadata

Higher layers replace lower layers field by field. For example, a runtime title replaces the route title without replacing the route description. The sections that follow describe how to set metadata at each layer. For information about rendering the resolved metadata, see Rendering.

Defining Metadata

Head allows you to define metadata using site-wide defaults, route metadata, runtime calls, and error page definitions.

Note

TypeScript has no named arguments, so wherever an argument is optional the last argument may be an object of options: Head.title('About', { suffix: ' - laraflare', exact: true }).

Defaults

Register page defaults in the boot method of a service provider:

import { Head, HeadBuilder, OgType } from '@laraflare/framework/head';

Head.defaults((head: HeadBuilder) => {
    head
        .title('laraflare', { suffix: ' - laraflare' })
        .description('Build something great.')
        .canonical()
        .og({ siteName: 'laraflare', type: OgType.Website })
        .searchableByRobots()
        .preconnect('https://fonts.example.com');
});

Defaults are the lowest-priority page metadata layer. If no route, runtime, or error metadata sets a title, laraflare renders as-is. When a higher layer sets a page title, the inherited suffix is applied, so Head.title('About') renders About - laraflare. Pass exact: true for titles that should ignore an inherited prefix or suffix.

Calling Head.canonical() renders a canonical URL using the current request URL. To set an explicit URL, pass a string such as Head.canonical('/about'). Canonical URLs are normalized to https by default; pass forceHttps: false to preserve the request scheme.

Robots directives may be passed as a raw string, as RobotsRule enum cases, or as a list mixing both forms. Lists are rendered as comma-separated directives, so Head.robots([RobotsRule.NoIndex, RobotsRule.NoFollow]) renders noindex, nofollow.

For convenience, the searchableByRobots method renders all, while the hiddenFromRobots method renders none.

Route Metadata

You may define metadata directly on routes, which is especially useful for semi-static pages whose metadata is known ahead of time.

Routes and Groups

Route.get('/contact', [ContactController, 'show'])
    .name('contact')
    .withHead({
        title: 'Contact Us',
        description: 'Get in touch.',
    });

Shared route metadata may be applied to a group at any position in the chain:

Route.withHead({ robots: 'noindex, nofollow' })
    .prefix('admin')
    .name('admin.')
    .group(() => {
        Route.get('/dashboard', DashboardController)
            .name('dashboard')
            .withHead({ title: 'Dashboard' });
    });

You may also define metadata for resource and singleton routes:

Route.resource('posts', PostController).withHead({
    robots: 'index, follow',
});

Route.singleton('profile', ProfileController).withHead({
    title: 'Your Profile',
});

The withHead method stores plain objects through the route's native metadata API. It is equivalent to calling the metadata method with the attributes nested under a head key, so the metadata remains compatible with cached routes.

The accepted keys are intentionally limited to Head's built-in route properties, and an unknown key throws an error so a misspelled name is caught. Route attributes registered by custom tag builders may be passed through extensions:

Route.get('/article', ArticleController).withHead({
    title: 'Article',
    extensions: { readingTime: 4 },
});

Supported Properties

The supported route properties map to the same names as the fluent builder methods:

Category Properties
Document title, description, canonical, robots
Application metadata themeColor, applicationName, colorScheme, referrer, viewport, appleWebAppTitle, webAppCapable, appleWebAppStatusBarStyle
Social og, ogImage, ogVideo, ogAudio, twitter, twitterImage
Performance preload, prefetch, preconnect, dnsPrefetch
Discovery alternates, feed, icon, favicon, appleTouchIcon, appleTouchStartupImage, maskIcon, manifest
Structured data schema
Custom tags meta, link

Nested option names use the same camelCase naming as the fluent API, such as forceHttps, siteName, and secureUrl.

Repeatable properties, such as ogImage, preload, feed, schema, icon, and appleTouchStartupImage, accept either a single value or a list.

Runtime Metadata

When a value isn't known until a request arrives, such as the title of a post being viewed, you may set it at runtime:

import { Head } from '@laraflare/framework/head';

async show(request: Request, post: Post) {
    Head.title(post.title);

    // ...
}

Runtime calls made via the Head facade override route metadata for request-dependent data. Controllers and actions are the most common places to make these calls:

import { Head } from '@laraflare/framework/head';

async show(request: Request, post: Post) {
    Head.title(post.title)
        .description(post.description);

    return Inertia.render('posts/Show', { post });
}

Multiple runtime calls are merged in the order they run. For single-value fields such as title, description, canonical URL, and robots directives, the later call takes precedence. Repeatable fields retain multiple entries, but adding the same key again updates the earlier entry. For the ogImage method, the URL is the key:

Head.ogImage('/images/cover.jpg', { alt: 'Draft cover' })
    .ogImage('/images/gallery.jpg', { alt: 'Gallery image' })
    .ogImage('/images/cover.jpg', { alt: 'Final cover', width: 1200, height: 630 });
<meta property="og:image" content="/images/cover.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Final cover">
<meta property="og:image" content="/images/gallery.jpg">
<meta property="og:image:alt" content="Gallery image">

Open Graph media inherited from your defaults acts as a fallback. When route, runtime, or error metadata defines its own media of the same type, the default media is replaced instead of merged, so a page's og:image takes precedence over a site-wide default image.

You may fluently define conditional metadata using the when and unless methods:

Head.title(post.title)
    .when(post.isDraft(), (head) => head.hiddenFromRobots());

Error Pages

Typically, you should register error metadata within the boot method of your application's AppServiceProvider class:

import { Head, ErrorPages } from '@laraflare/framework/head';

/**
 * Bootstrap any application services.
 */
override boot(): void {
    Head.errors((errors: ErrorPages) => {
        errors.defaults({ robots: 'noindex, follow' });

        errors.status(404, {
            title: 'Page Not Found',
            description: 'The page you are looking for could not be found.',
        });
    });
}

The defaults and status methods also accept the same fluent builder callback used by Head.defaults():

import { Head, ErrorPages, HeadBuilder } from '@laraflare/framework/head';

Head.errors((errors: ErrorPages) => {
    errors.status(404, (head: HeadBuilder) => head
        .title('Page Not Found')
        .description('The page you are looking for could not be found.'));
});

When a response is rendered for a registered error status, that metadata takes precedence over every other layer.

The head provider registers an exception renderer that sets the status from an HTTP exception's status code (any other exception is 500). If you render an error response inside your own exceptions.render() callback, call Head.status(404) before rendering so the error metadata is applied.

Open Graph

You may set Open Graph properties using the og method. Repeatable media may be added using the top-level methods, which accept an options object as their last argument:

import { Head, ImageType, OgType } from '@laraflare/framework/head';

Head.og({ type: OgType.Article, title: post.title })
    .ogImage(post.heroImageUrl)
    .ogImage(post.galleryImageUrl, {
        alt: post.galleryImageAlt,
        width: 1200,
        height: 630,
        type: ImageType.Jpeg,
    });

The ogImage, ogVideo, and ogAudio methods accept a URL as their first argument, along with optional options such as alt, width, height, type, and secureUrl where supported by the Open Graph specification.

You may pass image MIME types as ImageType enum cases anywhere the API accepts an image type, such as ImageType.Svg, ImageType.Png, ImageType.Jpeg, and ImageType.Webp.

For a single Open Graph image with no other attributes, you may pass the image option to the og method:

Head.og({
    type: OgType.Website,
    title: page.title,
    description: page.description,
    image: page.ogImageUrl,
});

The og({ image }) and ogImage(...) calls write to the same underlying image list, so you may use whichever is more expressive at the call site. You may use the meta method for custom Open Graph extensions such as product or article properties.

Note

Document title and description automatically fill missing og:title and og:description values.

When a page renders Open Graph tags without a url, Head uses the page's canonical URL as the og:url value. Since the canonical URL is resolved for each request, you may register both in your defaults:

import { Head, HeadBuilder, OgType } from '@laraflare/framework/head';

Head.defaults((head: HeadBuilder) => head
    .canonical()
    .og({ siteName: 'laraflare', type: OgType.Website }));

For a request to /pricing, this renders:

<link rel="canonical" href="https://example.com/pricing">
<meta property="og:type" content="website">
<meta property="og:site_name" content="laraflare">
<meta property="og:url" content="https://example.com/pricing">

If no canonical URL is set, og:url is omitted. An explicit url passed to the og method always takes precedence over the canonical URL.

X / Twitter Cards

To render X / Twitter cards from the same title, description, and image used by Open Graph, register twitter() in your defaults:

import { Head, HeadBuilder, TwitterCard } from '@laraflare/framework/head';

Head.defaults((head: HeadBuilder) => head.twitter({
    card: TwitterCard.SummaryWithLargeImage,
}));

Then set page-level metadata:

Head.title('Introducing Head')
    .description('A fluent API for document head metadata.')
    .ogImage('https://example.com/social.jpg', { alt: 'Introducing Head' });

This renders matching Twitter tags:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Introducing Head">
<meta name="twitter:description" content="A fluent API for document head metadata.">
<meta name="twitter:image" content="https://example.com/social.jpg">
<meta name="twitter:image:alt" content="Introducing Head">

You may customize individual pages with explicit Twitter values:

Head.twitter({ title: post.socialTitle })
    .twitterImage(post.socialImageUrl, { alt: post.title });

Route metadata accepts twitter and twitterImage.

Theme Colors

You may set theme colors globally, per route, or at runtime:

Head.themeColor('#0f172a');

This renders a <meta name="theme-color"> tag. For media-specific theme colors, you may use the Media enum:

import { Media } from '@laraflare/framework/head';

Head.themeColor('#ffffff', Media.Light)
    .themeColor('#111827', Media.Dark);

The Media enum also includes Portrait and Landscape. The media argument also accepts a custom media query string.

Route metadata supports a single theme color through the same camelCase key:

Route.get('/dashboard', DashboardController).withHead({
    themeColor: '#0f172a',
});

Application Metadata and Icons

Head includes methods for common browser and application metadata:

import { Head, ImageType, Media } from '@laraflare/framework/head';

Head.applicationName('laraflare')
    .colorScheme('light dark')
    .referrer('strict-origin-when-cross-origin')
    .viewport('width=device-width, initial-scale=1')
    .appleWebAppTitle('laraflare')
    .webAppCapable()
    .appleWebAppStatusBarStyle('black')
    .favicon('/favicon.svg', ImageType.Svg)
    .icon('/favicon-32x32.png', ImageType.Png, '32x32')
    .appleTouchIcon('/apple-touch-icon.png', '180x180')
    .appleTouchStartupImage('/launch.png', Media.Portrait)
    .maskIcon('/safari-pinned-tab.svg', '#111827')
    .manifest('/site.webmanifest');

The favicon method is an alias for the icon method and accepts the same type, sizes, and media arguments, in that order.

Route metadata uses the same names:

import { ImageType, Media } from '@laraflare/framework/head';

Route.get('/dashboard', DashboardController).withHead({
    applicationName: 'laraflare',
    colorScheme: 'light dark',
    appleWebAppTitle: 'laraflare',
    webAppCapable: true,
    appleWebAppStatusBarStyle: 'black',
    favicon: [
        { href: '/favicon.svg', type: ImageType.Svg },
        { href: '/favicon-32x32.png', type: ImageType.Png, sizes: '32x32' },
    ],
    appleTouchIcon: { href: '/apple-touch-icon.png', sizes: '180x180' },
    appleTouchStartupImage: { href: '/launch.png', media: Media.Portrait },
    manifest: '/site.webmanifest',
});

Progressive Web Apps

The pwa method configures the common document <head> tags needed for an installable web app:

Head.pwa('laraflare', {
    manifest: '/site.webmanifest',
    themeColor: '#0f172a',
    appleTouchIcon: '/apple-touch-icon.png',
    appleWebAppStatusBarStyle: 'black',
});

This renders the application name, web application manifest link, and iOS standalone metadata. If provided, the theme color, Apple status bar style, and Apple touch icon are also rendered. Creating the web application manifest and registering a service worker remain your application's responsibility.

You may use the pwa method in defaults or runtime metadata. Route metadata supports the individual properties shown above.

Performance and Discovery

Head renders performance hints, pagination links, locale alternates, and feed discovery:

Head.preload(asset('fonts/inter.woff2'), { as: 'font', crossorigin: true })
    .prefetch(asset('images/next.webp'))
    .preconnect('https://cdn.example.com')
    .dnsPrefetch('https://analytics.example.com')
    .paginate(posts)
    .alternates({
        'en': 'https://example.com/en/about',
        'fr': 'https://example.com/fr/about',
        'x-default': 'https://example.com/about',
    })
    .feed('/feed', { title: 'laraflare RSS' })
    .feed('/feed.atom', { type: 'atom', title: 'laraflare Atom' });

For local assets, preloadAsset() and prefetchAsset() resolve the URL through the asset() helper and detect the as attribute from the file extension. Font preloads automatically include crossorigin, which the preload specification requires even for same-origin fonts:

Head.preloadAsset('fonts/inter.woff2')
    .prefetchAsset('images/next.webp');
<link rel="preload" href="https://example.com/fonts/inter.woff2" as="font" crossorigin>
<link rel="prefetch" href="https://example.com/images/next.webp" as="image">

You may pass as explicitly to override detection. The preloadAsset method will throw an exception when the as attribute cannot be detected from the extension because browsers ignore preloads without this attribute; the prefetchAsset method will simply omit it.

Custom Tags

For tags without a dedicated method, use meta() and link():

Head.meta('format-detection', 'telephone=no')
    .meta('article:author', post.author.name)
    .link('search', '/opensearch.xml', {
        type: 'application/opensearchdescription+xml',
        title: 'laraflare Search',
    })
    .link('me', 'https://social.example.com/@laraflare');

You may include a media query on a meta tag when the browser should only apply the tag under matching conditions:

import { Media } from '@laraflare/framework/head';

Head.meta('theme-color', '#ffffff', { media: Media.Light })
    .meta('theme-color', '#111827', { media: Media.Dark });

The meta method uses the name attribute for regular meta tags. For keys that typically use the property attribute, such as Open Graph (og:) or article metadata (article:), the method switches automatically:

Head.meta('description', 'About laraflare')
    .meta('og:title', 'About laraflare');
<meta name="description" content="About laraflare">
<meta property="og:title" content="About laraflare">

You may pass property: true or property: false in the options to explicitly select either attribute.

Schemas

Built-in schema builders cover the common JSON-LD types:

import { Head, OfferAvailability, Schema } from '@laraflare/framework/head';

Head.schema(
    Schema.product()
        .name(product.name)
        .offers(
            Schema.offer()
                .price(product.price)
                .currency('USD')
                .availability(OfferAvailability.InStock)
        )
);

The built-in factory methods are article, blogPosting, event, product, offer, brand, breadcrumbs, faq, organization, person, place, webPage, and webSite. Unknown factory methods create a generic schema object, so you can still express custom schema.org types.

When JSON-LD schema data is invalid, Head throws an InvalidSchema exception in non-production environments and logs a warning in production.

Breadcrumbs

Breadcrumb items may be added one at a time or in bulk. Positions are assigned automatically in the order the items are added:

Head.schema(
    Schema.breadcrumbs().items({
        'Home': route('home'),
        'Shop': route('shop.index'),
        'Shoes': route('shop.category', 'shoes'),
    })
);

You may use the item method to append a single breadcrumb item:

Schema.breadcrumbs()
    .item('Home', route('home'))
    .item('Shop', route('shop.index'));

FAQs

FAQ entries follow the same pattern. You may add them one at a time using the question method or in bulk using the questions method:

Head.schema(
    Schema.faq().questions({
        'What is Head?': 'A fluent API for managing the document head.',
        'Is it free?': 'Yes, it is open source.',
    })
);

Custom Schemas

You may explicitly register custom schema types:

import { Head, Schema, SchemaObject, SchemaType } from '@laraflare/framework/head';

@SchemaType('JobPosting')
class JobPosting extends SchemaObject {
    title(title: string): this {
        return this.set('title', title);
    }

    datePosted(date: Date | string): this {
        return this.date('datePosted', date);
    }
}

Schema.register(JobPosting);

Head.schema(
    Schema.jobPosting()
        .title('Senior Developer')
        .datePosted(new Date())
);

Rendering

Head resolves page metadata into tags for the current response. The HTML renderer powers Head.render() and Head.toHtml(), and Head.toElements() returns the tags as a list of element strings. The array renderer powers Head.toArray() for applications that need the resolved metadata as structured data, including titles, Open Graph values, JSON-LD schemas, and other resolved metadata.

The screens of a laraflare application are Vue components, so there is no template directive for the head: the resolved tags are available to whatever builds your document.

const html = Head.toHtml();
const elements = Head.toElements();
const metadata = Head.toArray();

Define page metadata before the document is rendered, since the tags are resolved when you ask for them.

Inertia

For Inertia pages, Head.toInertiaElements() returns the page-managed head as an array of rendered element strings, each with a stable data-inertia key, so the client can adopt those elements and keep them synchronized during visits. The elements are named head by default; if your application already uses that prop name, change it in a service provider:

import { Head } from '@laraflare/framework/head';

override boot(): void {
    Head.inertia('_head');
}

Note

When adding Head to an existing Inertia application, move tags managed by Inertia's <Head> component into Head so the two never define the same element.

Static Inertia Tags

Most tags should live in defaults, route metadata, or runtime metadata so Head can resolve the right value for each page. Use Inertia globals only for document tags rendered in the first HTML response and left unchanged by Inertia for the rest of the session.

Register them in a service provider with Head.inertiaGlobals():

import { Head, HeadBuilder } from '@laraflare/framework/head';

Head.inertiaGlobals((head: HeadBuilder) => {
    head
        .viewport('width=device-width, initial-scale=1')
        .colorScheme('light dark')
        .icon('/favicon.svg', 'image/svg+xml')
        .appleTouchIcon('/apple-touch-icon.png', '180x180')
        .manifest('/site.webmanifest');
});

Inertia globals are excluded from the page-managed elements, rendered without data-inertia ownership attributes, and never updated after the first response. These globals are suitable for stable browser hints such as viewport, color scheme, favicons, touch icons, and manifests. If a tag is page-specific, SEO-relevant, or may be overridden later, put it in defaults, route metadata, or runtime metadata instead.

Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.