Understanding Metadata Optimization
Designing an Effective Architecture
Real‑World Implementation – Code Examples
const app = express(); app.use(bodyParser.json());
const redis = new Redis({ host: 'redis-cache', port: 6379 });
// Register Handlebars engine for templates app.engine('hbs', exphbs({ extname: '.hbs' })); app.set('view engine', 'hbs'); app.set('views', __dirname + '/templates');
</pre> <h3>2. Template Example (title.hbs)</h3> <pre> handlebars <title>{{seo.title}}</title> <meta name="description" content="{{seo.description}}" /> <link rel="canonical" href="{{canonical}}" /> {{#if og}} <meta property="og:title" content="{{og.title}}" /> <meta property="og:description" content="{{og.description}}" /> <meta property="og:image" content="{{og.image}}" /> {{/if}} {{#if jsonld}} <script type="application/ld+json">{{{jsonld}}}</script> {{/if}} </pre> <h3>3. Generating Metadata on Webhook</h3> <pre> ```javascript app.post('/webhook/content-published', async (req, res) => { const { id, slug, title, excerpt, author, tags, publishedAt } = req.body; ```// Build SEO data structure
const seo = {
title: ${title} | MyBrand,
description: excerpt.slice(0, 155),
};
const canonical = https://www.mybrand.com/${slug};
const og = {
title: seo.title,
description: seo.description,
image: https://cdn.mybrand.com/images/${slug}.jpg,
};
// JSON‑LD for Article const jsonld = JSON.stringify({ '@context': 'https://schema.org', '@type': 'Article', headline: title, author: { '@type': 'Person', name: author }, datePublished: publishedAt, image: og.image, keywords: tags.join(', '), });
// Render the Handlebars template const htmlMeta = await app.render('title', { seo, canonical, og, jsonld });
// Cache for fast retrieval
await redis.set(meta:${id}, htmlMeta, 'EX', 60 * 60 * 24);
res.status(200).json({ success: true, meta: htmlMeta }); });
</pre> <h3>4. Retrieving Cached Metadata on Page Render</h3> <pre> ```javascript app.get('/article/:slug', async (req, res) => { const { slug } = req.params; const article = await fetchArticleFromCMS(slug); // custom function const cachedMeta = await redis.get(`meta:${article.id}`); ```const meta = cachedMeta || '<!-- meta not generated yet -->';
// Inject meta into HTML template sent to the browser
res.send( <!DOCTYPE html> <html lang="en"> <head> ${meta} <link rel="stylesheet" href="/styles/main.css" /> </head> <body> <article> <h1>${article.title}</h1> <p>${article.body}</p> </article> </body> </html> );
});
