Sub topic 11
Generating Tags per Page Safely
This chapter assumes you know the basic Open Graph properties (og:title, og:type, og:url, og:image), how absolute and relative URLs differ, and how a server or template engine renders HTML. Here you will build Open Graph tags from page data in code. The focus is on escaping, URL handling, fallbacks, and keeping the tags in the HTML that crawlers fetch.
Why static tags are not enough
A hand-written <head> works for one page. A blog, shop, or documentation site has hundreds or thousands of pages, and each one needs its own title, description, canonical URL, and image. If every page shares the same tags, every shared link looks identical in a feed.
The fix is to treat Open Graph tags as output computed from the same data that renders the page. The page record (a post, a product, a document) is the single source of truth. A function turns that record into meta tags. Because the function runs on the server, the tags are present in the first HTML response, which is what crawlers read.
The risk: untrusted values in attributes
Titles and descriptions often come from users, editors, or imported content. Placing them in an attribute without escaping causes two kinds of problems.
- Broken markup. A title such as
The "Best" Coffeeends thecontent="..."attribute early. The crawler may read a truncated title, or ignore the tag. - Injection. A value such as
"><script>alert(1)</script>closes the tag and adds a script. This is cross-site scripting (XSS). Social crawlers do not run scripts, but real visitors who load the page do.
The rule is to escape every dynamic value for the context where it lands. Inside a double-quoted attribute, you must escape &, <, >, and ". Escape & first, otherwise you would double-escape the entities you just produced.
A safe tag builder
This helper takes a page object and returns the tag string. It escapes every value, including the property name's value side, and skips empty values so you never emit content="".
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
.filter(([, content]) => content !== undefined && content !== null && content !== "")
.map(([property, content]) => `<meta property="${property}" content="${escapeHtml(content)}">`)
.join("\n");
}
console.log(
openGraphTags({
title: 'The "Best" Cold Brew & More',
description: "Smooth coffee at home.",
url: "https://example.com/cold-coffee",
image: "https://example.com/images/cold-coffee-1200x630.jpg",
})
);Running this prints the title as The "Best" Cold Brew & More. A crawler decodes those entities back to the original text, so the preview card shows the title as the author wrote it. Entities are not double-decoded, so do not escape a value twice. If your data store already holds HTML-escaped text, decode it before passing it in.
The filter step is part of the design. A missing description should produce no tag, not an empty one. Platforms treat a missing tag and an empty tag differently, and an empty og:image can stop them from falling back to another image source.
Prefer your template engine's escaping
Many template engines (Jinja, Nunjucks, Handlebars, Blade, Razor, JSX) escape output by default. If you use one, write the tag in the template and let the engine escape the value. Writing your own escaper is only worth it when you build strings by hand, as above. The mistake to watch for is switching escaping off (|safe, triple braces, dangerouslySetInnerHTML) to "fix" a display problem. That removes the protection for exactly the values you least control.
Normalize before you render
Escaping makes values safe. It does not make them good. Normalize page data first.
Absolute URLs
og:url and og:image must be absolute URLs, including the scheme and host. A relative path such as /images/a.jpg has no meaning to a crawler that is not browsing your site. Build absolute URLs from one configured base, not from the incoming request's Host header. Request headers can be forged, and behind a proxy they often show an internal hostname.
const SITE_ORIGIN = "https://example.com";
function absoluteUrl(path) {
return new URL(path, SITE_ORIGIN).toString();
}
console.log(absoluteUrl("/images/cold-coffee-1200x630.jpg"));
// https://example.com/images/cold-coffee-1200x630.jpg
console.log(absoluteUrl("https://cdn.example.com/a.jpg"));
// https://cdn.example.com/a.jpgnew URL(path, base) handles both cases. A relative path is resolved against the origin, and an already absolute URL passes through unchanged. It also throws on malformed input, which is better than silently shipping a broken tag.
Canonical `og:url`
og:url should be the canonical address of the page. It should not include tracking parameters such as utm_source, session IDs, or sort and filter options that do not change the content. Platforms use this value to merge shares of the same page. If every share link carries a different og:url, likes and share counts are split across many copies.
Compute it from the page's identity (its slug or ID), not from the URL the visitor happened to request.
Length and whitespace
Platforms truncate long text, and the cutoff varies. A title around 60 to 70 characters and a description around 150 to 200 characters usually display in full. Collapse runs of whitespace and strip markup from descriptions that come from rich text. Trim at a word boundary and add an ellipsis rather than cutting a word in half.
function toPlainSnippet(text, max = 160) {
const clean = String(text).replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
if (clean.length <= max) return clean;
const cut = clean.slice(0, max - 1);
return cut.slice(0, cut.lastIndexOf(" ") > 0 ? cut.lastIndexOf(" ") : cut.length) + "…";
}The tag-stripping regex here is only for building a short text snippet. It is not a sanitizer. The result still goes through escapeHtml before it reaches an attribute.
Fallbacks for missing data
Real data is incomplete. Decide in code what happens when a field is absent, so the output is predictable.
| Missing field | Reasonable fallback |
|---|---|
| Description | A snippet of the page body, then the site-wide default |
| Page image | A site-wide default image at the recommended size |
| Image alt text | The page title, or omit `og:image:alt` |
| Title | Site name (never an empty tag) |
A default image matters most. A page with no og:image gets a small text-only card on most platforms, which draws fewer clicks. A branded fallback image is a better outcome than none.
const DEFAULTS = {
title: "Example Coffee",
description: "Recipes and guides for better coffee.",
image: "https://example.com/images/default-1200x630.jpg",
imageAlt: "Example Coffee logo on a dark background",
};
function ogForPage(page) {
const description = page.summary || (page.body ? toPlainSnippet(page.body) : "") || DEFAULTS.description;
const hasImage = Boolean(page.image);
return {
title: page.title || DEFAULTS.title,
description,
url: absoluteUrl(`/${page.slug}`),
image: absoluteUrl(hasImage ? page.image : DEFAULTS.image),
imageAlt: hasImage ? page.imageAlt : DEFAULTS.imageAlt,
};
}Notice that imageAlt follows the image. If you swap in the default image but keep the page's alt text, the alt text describes a picture the card does not show.
Choosing the type per page
Pick og:type from the kind of page, not one site-wide value. A lookup keeps the decision in one place.
function extraTags(page) {
if (page.kind !== "article") return `<meta property="og:type" content="website">`;
const lines = [`<meta property="og:type" content="article">`];
if (page.publishedAt) {
const iso = new Date(page.publishedAt).toISOString();
lines.push(`<meta property="article:published_time" content="${escapeHtml(iso)}">`);
}
for (const tag of page.tags || []) {
lines.push(`<meta property="article:tag" content="${escapeHtml(tag)}">`);
}
return lines.join("\n");
}Repeatable properties such as article:tag are emitted once per value, not as a comma-separated list. toISOString() produces the ISO 8601 form that article:published_time expects, and it throws a RangeError on an invalid date. Validate dates when they are saved, not when a crawler requests the page.
If you combine extraTags with openGraphTags, drop the hard-coded og:type from the builder, or you will output two og:type tags and platforms may pick either one.
Keep tags in the server response
Crawlers such as the ones behind Facebook, LinkedIn, and Slack do not run your JavaScript. If a client-side script inserts the Open Graph tags after the page loads, the crawler never sees them. Generate the tags on the server, either during server-side rendering or at build time for a static site.
Single-page applications need extra care. A common approach is to detect crawler user agents and return a pre-rendered head for them. A simpler and more reliable approach is server-side rendering or pre-rendering the routes that people share. Either way, confirm the result by requesting the page the way a crawler would:
curl -s -A "facebookexternalhit/1.1" https://example.com/cold-coffee | grep -i 'property="og:'If the command prints nothing, the tags are not in the initial HTML, whatever your browser's developer tools show after scripts have run.
Edge cases
- Duplicate tags. A layout and a page template can each emit
og:title. Have one function own all Open Graph output and let templates pass data to it. - Unpublished or private pages. A crawler that fetches a private URL without credentials receives a login page. Its preview will show the login page's title. Do not put private titles or descriptions in tags on pages you serve to anonymous requests.
- Encoding. Declare
<meta charset="utf-8">early in the<head>and serve the HTML as UTF-8. Otherwise non-ASCII titles may show as garbled characters. - Caching. If tags are generated per request from changing data, the platform still caches what it first fetched. Changing the data does not refresh existing previews. See the chapter on testing and cache refresh.
- Double escaping. Output like
&amp;in the preview means a value was escaped twice, once in your data layer and once in the tag builder.
Testing the generator
Because the builder is a plain function, you can test it without a browser. Check three things: special characters are escaped, empty fields are omitted, and URLs are absolute.
const assert = require("node:assert");
const out = openGraphTags({
title: '"><script>x</script>',
description: "",
url: "https://example.com/a",
image: "https://example.com/a.jpg",
});
assert(!out.includes("<script>"));
assert(out.includes(""><script>"));
assert(!out.includes("og:description"));
assert(out.includes('content="https://example.com/a.jpg"'));
console.log("ok");This test places the injection string from earlier into the title and confirms that it comes out as inert text.
Summary of the rules
- Generate tags on the server so they appear in the first HTML response.
- Escape every dynamic value for a double-quoted attribute,
&first. - Build absolute URLs from a configured origin, not from request headers.
- Compute
og:urlfrom the page's identity, without tracking parameters. - Omit empty tags and define fallbacks for description and image.
- Emit exactly one
og:typeper page, and one tag per value for repeatable properties. - Test the builder with hostile input.
Exercise
A page title in your database is Tom & Jerry's "Big" Day. Your builder outputs <meta property="og:title" content="Tom & Jerry's "Big" Day">. What goes wrong, and what should the output be?
Show answer
The unescaped double quotes end the content attribute after Tom & Jerry's , so the crawler reads a truncated title and the rest of the text becomes stray markup. The bare & is also invalid. The output should be <meta property="og:title" content="Tom & Jerry's "Big" Day">. The apostrophe is safe in a double-quoted attribute. Fix it by passing the value through an escaping function that replaces & first, then <, >, and ".
Exercise
Your site sets og:url from the URL the visitor requested. Shares of the same article arrive as /post?utm_source=mail and /post?utm_source=chat. Why is this a problem, and how do you fix it?
Show answer
Each variant has a different og:url, so platforms treat them as different pages and split share counts and cached previews between them. Compute og:url from the page's slug or ID against a configured site origin, such as https://example.com/post, so every share variant reports the same canonical address.
Exercise
Your Open Graph tags are added by a React component after the page loads. Facebook's debugger shows no tags, though your browser shows them in developer tools. Why, and what are two fixes?
Show answer
Social crawlers do not run JavaScript, so they only see the initial HTML, which lacks the tags. Fix it by rendering the head on the server (server-side rendering) or by pre-rendering the shareable routes at build time. You can confirm the fix with curl -s -A "facebookexternalhit/1.1" URL | grep -i 'property="og:'.