Sub topic 11
Generating Tags per Page Safely
This chapter assumes you know basic HTML, the difference between absolute and relative URLs, and how a server renders a page from a template. It also assumes you have seen the core Open Graph properties (og:title, og:type, og:url, og:image) from earlier chapters.
Why generate tags in code
A site with ten pages can hand-write ten sets of tags. A blog, shop, or docs site cannot. Each page has its own title, description, URL, and image, so the server builds the tags from page data when it renders the HTML.
The tags must be in the HTML the server sends. Social crawlers usually do not run JavaScript, so tags that a browser script adds after load are not seen.
Why escaping matters
Page titles come from editors, users, or a database. A title such as Tom & Jerry's "Best" <Brews> contains characters that have meaning in HTML. If you place it unescaped inside content="...", the first double quote ends the attribute early. The rest of the title becomes stray markup, and the preview breaks or shows truncated text.
Unescaped values are also a security problem. If a value can contain "><script>, an attacker can inject their own markup into your page. This is cross-site scripting (XSS). Escaping every value at the point of output prevents it.
Escape these four characters:
| Character | Escaped form |
|---|---|
| `&` | `&` |
| `<` | `<` |
| `>` | `>` |
| `"` | `"` |
Escape & first. If you escape it last, you would turn the & in < into &lt;.
A tag helper
This helper takes page data and returns the tag block. It escapes every value, including the URL and image.
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function openGraphTags({ title, description, url, image, imageAlt }) {
const props = [
["og:title", title],
["og:type", "website"],
["og:url", url],
["og:image", image],
["og:image:alt", imageAlt],
["og:description", description],
];
return props
.map(([property, content]) => `<meta property="${property}" content="${escapeHtml(content)}">`)
.join("\n");
}Call it inside your template, for example:
const head = openGraphTags({
title: 'Tom & Jerry\'s "Best" Brews',
description: "A simple method for smooth cold-brew coffee at home.",
url: "https://example.com/cold-coffee",
image: "https://example.com/images/cold-coffee-1200x630.jpg",
imageAlt: "A glass of cold brew coffee with ice on a wooden table",
});
console.log(head);The first line of output is:
<meta property="og:title" content="Tom & Jerry's "Best" Brews">The browser and crawler decode the entities, so the preview shows the original title.
Building absolute URLs
og:url and og:image must be absolute. Crawlers do not know which site a relative path belongs to. Store a single site origin in configuration and join it with each page's path.
const SITE_ORIGIN = "https://example.com";
function absoluteUrl(path) {
return new URL(path, SITE_ORIGIN).href;
}
console.log(absoluteUrl("/cold-coffee"));
// https://example.com/cold-coffeeUsing new URL handles missing or doubled slashes. Do not build the origin from the incoming request's Host header, because a client can send any value there. A fixed configured origin also keeps og:url stable, so the same page shared through different hostnames produces one canonical URL.
Defaults and fallbacks
Some pages will lack a description or image. Decide what happens in the helper, not in each template:
- If there is no image, use a site-wide default image, not an empty
contentvalue. - If there is no description, use a default site description, or omit the tag.
- Trim long descriptions to a sensible length, around 150 to 200 characters, before escaping. Trim first so you never cut an entity such as
&in half. - Omit a tag when its value is empty. An empty
og:imagecan make a platform show no image at all.
Common errors
- Escaping twice. If your template engine escapes output automatically, running
escapeHtmlfirst produces&amp;and the preview shows literal&. Escape in exactly one place. - Escaping too late or not at all. Building tags with string concatenation in a framework that does not auto-escape is the usual source of broken titles.
- Relative image paths.
/images/a.jpgworks in a browser but not for a crawler. - Tags set client-side. A single-page app that sets tags after load needs server-side rendering or pre-rendering for those pages.
Exercise
A page title is 5 < 10 & "easy". Write the escaped value that goes inside content="...", and explain why & must be replaced before <.
Show answer
The escaped value is 5 < 10 & "easy". If < were replaced first, the result < contains an &, and a later & replacement would change it into &lt;. Replacing & first avoids escaping the entities you just created.
Exercise
Your helper receives image: "/images/a.jpg" and the site origin is https://example.com. Which function call produces a valid og:image value, and why not use the request's Host header?
Show answer
absoluteUrl("/images/a.jpg") returns https://example.com/images/a.jpg. The Host header is supplied by the client and can be forged, so using it could produce wrong or attacker-chosen URLs. A configured origin is fixed and trusted.