OG Εικόνες από έναν Express Server
Δημιουργήστε OG εικόνες στο Express με το συνδρομητικό Dynamic API της FastOG — με μια συνδρομή στο Dynamic API (δημιουργήστε το κλειδί API σας στον πίνακα ελέγχου). Κάντε προεπισκόπηση οποιουδήποτε προτύπου στο Δωρεάν OG Image Tester και, στη συνέχεια, εξυπηρετήστε δυναμικές εικόνες Open Graph από τον Express server σας με υπογεγραμμένα HMAC URLs.
Ρύθμιση
bash
npm install express
Υλοποίηση
javascript
// app.js
import express from "express";
import crypto from "crypto";
import { URL } from "url";
const app = express();
function generateSignedOgUrl(params, options = {}) {
const {
baseUrl = "https://fastog.com/api/v1/og",
apiKey = process.env.FASTOG_API_KEY,
hmacSecret = process.env.FASTOG_HMAC_SECRET,
} = options;
// RFC-3986 percent-encoding: keep A-Za-z0-9-._~
const enc = (s) =>
encodeURIComponent(s).replace(
/[!'()*]/g,
(c) => "%" + c.charCodeAt(0).toString(16).toUpperCase(),
);
// Every query param except the signature, INCLUDING key
const all = { ...params, key: apiKey };
// Canonical query: sorted enc(key)=enc(value) pairs joined with &
const pairs = [];
for (const [k, v] of Object.entries(all)) {
for (const vv of Array.isArray(v) ? v : [v]) {
pairs.push(`${enc(k)}=${enc(vv)}`);
}
}
pairs.sort();
const canonical = pairs.join("&");
// Sign the exact bytes the server will verify
const signature = crypto
.createHmac("sha256", hmacSecret)
.update(`GET/api/v1/og\n${canonical}`)
.digest("hex");
// Build the URL from the same pairs so bytes match the canonical form
const url = new URL(baseUrl);
for (const [k, v] of Object.entries(all)) {
for (const vv of Array.isArray(v) ? v : [v]) {
url.searchParams.append(Array.isArray(v) ? `${k}[]` : k, vv);
}
}
url.searchParams.set("s", signature);
return url.toString();
}
// Blog post route
app.get("/blog/:slug", async (req, res) => {
const post = await getPost(req.params.slug);
const ogImageUrl = generateSignedOgUrl({
template: "blog",
title: post.title,
subtitle: post.excerpt,
});
res.render("blog/post", {
post,
ogImageUrl,
});
});
// API endpoint for dynamic OG images
app.get("/api/og", (req, res) => {
const { title, template = "default" } = req.query;
if (!title) {
return res.status(400).json({ error: "Missing title" });
}
const ogImageUrl = generateSignedOgUrl({
template,
title,
});
res.json({ ogImageUrl });
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Πρότυπο EJS
ejs
<!-- views/blog/post.ejs -->
<!DOCTYPE html>
<html>
<head>
<meta property="og:image" content="<%= ogImageUrl %>" />
<meta property="og:title" content="<%= post.title %>" />
<meta property="og:description" content="<%= post.excerpt %>" />
</head>
<body>
<h1><%= post.title %></h1>
</body>
</html>
Πρότυπο Pug
pug
// views/blog/post.pug
doctype html
html
head
meta(property="og:image" content=ogImageUrl)
meta(property="og:title" content=post.title)
meta(property="og:description" content=post.excerpt)
body
h1= post.title
Προσέγγιση Middleware
Αυτό προϋποθέτει ότι έχετε μεταφέρει τη συνάρτηση generateSignedOgUrl από το app.js στο lib/og-image-signer.js και την έχετε εξάγει.
javascript
// middleware/og-image.js
import { generateSignedOgUrl } from "../lib/og-image-signer.js";
export function injectOgImage(template, titleFn) {
return (req, res, next) => {
const originalRender = res.render.bind(res);
res.render = function (view, locals) {
const title = titleFn(locals);
locals.ogImageUrl = generateSignedOgUrl({
template,
title,
});
return originalRender(view, locals);
};
next();
};
}
// Usage
app.get(
"/blog/:slug",
injectOgImage("blog", (locals) => locals.post.title),
async (req, res) => {
const post = await getPost(req.params.slug);
res.render("blog/post", { post });
},
);
Μεταβλητές Περιβάλλοντος
bash
# .env
FASTOG_API_KEY=sk_your_full_api_key_here
FASTOG_HMAC_SECRET=your_64_char_hex_secret_here