@mailoo/blog
v1.35.9
Published
Headless Mailoo Blog module for Next.js (BFF routes, server client, components)
Downloads
4,725
Readme
@mailoo/blog
Headless Mailoo Blog module for Next.js apps.
Install
pnpm add @mailoo/blog @mailoo/next-corehttps://www.npmjs.com/package/@mailoo/blog
Env (server-only)
MAILOO_BLOG_API=
MAILOO_BLOG_API_KEY=
MAILOO_BLOG_PROJECT_UID=
MAILOO_BLOG_INTEGRATION_ID=The API key needs blog.external-read for GET routes, blog.article-mark
for like/dislike/feedback POST routes, and image.external-read when the
host proxies cover/body images (or FULL).
Pass imageProxyPrefixWithIdEquals so list, slug, category description, and
JSON-LD image URLs point at your BFF instead of the canonical Mailoo embed
URL (that URL is 401 without X-API-Key):
const client = createMailooBlogClient(config, {
imageProxyPrefixWithIdEquals: '/api/v1/images/public/content?id=',
})A site-relative prefix is copied onto rewritten ogImageUrl and image URLs
in htmlContent / JSON-LD. Leave those paths as <img src>. Do not pass
post.ogImageUrl into openGraph.images as-is. Absolutize against the
current request origin (X-Forwarded-Host or Host, plus
X-Forwarded-Proto). Do not bake a fixed SITE_URL into this option.
Without metadataBase, Next.js emits http://localhost:3000/….
Facebook needs absolute https://; MIME image/jpeg | image/gif |
image/png; and og:image:type / width / height (min 200×200, max
8 MB). The package does not supply width/height — probe the proxy (Range
bytes=0-524288).
Allow the proxy path in the * robots group for Twitter/LinkedIn and
RFC 9309. That is not enough for Facebook: Disallow: /api/ wins over
Allow: /api/v1/mailoo-image and the debugger reports a synthetic 403
even when the origin returned 200. Add User-agent: facebookexternalhit
/ Allow: /. Do not expect that group to override Disallow: /api/ —
omit Disallow: /api/ or serve the proxy outside /api/.
import { headers } from 'next/headers'
async function requestOrigin(): Promise<string> {
const h = await headers()
const host = h.get('x-forwarded-host') ?? h.get('host')
if (!host) {
throw new Error('Request host is required to build absolute og:image URLs')
}
const proto = h.get('x-forwarded-proto') ?? 'https'
return `${proto}://${host}`
}
function absoluteSocialImageUrl(imageUrl: string, origin: string): string {
if (/^https?:\/\//i.test(imageUrl)) return imageUrl
return new URL(imageUrl, `${origin}/`).toString()
}
async function probeOgImage(imageUrl: string): Promise<{
url: string
secureUrl: string
type: 'image/jpeg' | 'image/gif' | 'image/png'
width: number
height: number
}> {
const res = await fetch(imageUrl, {
headers: { Range: 'bytes=0-524288' },
})
if (!res.ok && res.status !== 206) {
throw new Error(`og:image probe failed: HTTP ${res.status}`)
}
const type = (res.headers.get('content-type') ?? '')
.split(';')[0]
?.trim()
.toLowerCase()
if (type !== 'image/jpeg' && type !== 'image/gif' && type !== 'image/png') {
throw new Error(
`og:image type must be jpeg, gif or png, got ${type || 'missing'}`
)
}
// Host: parse PNG IHDR / JPEG SOF / GIF header of the body.
const { width, height } = parseImageDimensions(
new Uint8Array(await res.arrayBuffer())
)
return { url: imageUrl, secureUrl: imageUrl, type, width, height }
}
const origin = await requestOrigin()
const absolute = post.ogImageUrl
? absoluteSocialImageUrl(post.ogImageUrl, origin)
: undefined
const image = absolute ? await probeOgImage(absolute) : undefinedMount createPublicImageContentHandler from @mailoo/images/routes on that
path. Omit the option to keep canonical URLs for server-only callers.
rewriteMailooBlogMediaUrls does the same rewrite for a single article.
Usage
BFF routes
// app/api/v1/blog/route.ts
import { createBlogListHandler } from '@mailoo/blog/routes'
export const GET = createBlogListHandler({
imageProxyPrefixWithIdEquals: '/api/v1/images/public/content?id=',
resolveLocale: (request) => localeFromRequest(request),
})imageProxyPrefixWithIdEquals is the same option as on createMailooBlogClient.
List, slug, category-description, and JSON-LD responses rewrite canonical embed
URLs to that prefix. If the prefix is set and the body has no
imagePublicEmbedBaseUrl, the handler returns 502 and does not forward
the raw URLs. JSON-LD is rewritten by embed path on any host. Omit the option
to proxy the upstream JSON unchanged.
resolveLocale runs only when the query has no locale (list, slug,
categories, tags, category description, JSON-LD). The host maps
Accept-Language to its own locale list. A query locale wins.
// app/api/v1/blog/slug/[slug]/route.ts
import { createBlogSlugHandler } from '@mailoo/blog/routes'
export const GET = createBlogSlugHandler()// app/api/v1/blog/slug/[slug]/json-ld/route.ts
import { createBlogJsonLdHandler } from '@mailoo/blog/routes'
export const GET = createBlogJsonLdHandler()// app/api/v1/blog/slug/[slug]/reaction/route.ts
import { createBlogReactionHandler } from '@mailoo/blog/routes'
export const POST = createBlogReactionHandler()// app/api/v1/blog/slug/[slug]/feedback/route.ts
import { createBlogFeedbackHandler } from '@mailoo/blog/routes'
export const POST = createBlogFeedbackHandler()Server client / RSC helpers
import {
createMailooBlogClient,
getMailooBlogConfigFromEnv,
fetchBlogPostBySlug,
} from '@mailoo/blog/server'
const config = getMailooBlogConfigFromEnv()
if (config) {
const client = createMailooBlogClient(config)
const list = await client.listPosts({ limit: 20, locale })
if (list.ok) {
const posts = list.data
const { pagination, imagePublicEmbedBaseUrl } = list
}
const post = await client.getPostBySlug(slug, locale)
// Slug detail includes likeCount / dislikeCount / feedbackCount
const jsonLd = await client.getPostJsonLd(slug, locale)
await client.setReaction(slug, {
visitorKey,
action: 'set',
sentiment: 'LIKE',
})
await client.setFeedback(slug, {
visitorKey,
action: 'set',
comment: 'Helpful article',
})
}Use createMailooBlogClient (direct Mailoo API) from RSC, sitemap, and
other server jobs so they never loop back to the host BFF. Direct client
fetches use Next.js next: { revalidate: 60 } by default; pass
{ revalidate: 0 } (or another number) as the last argument to override.
listPosts keeps the API list envelope: data (posts array),
pagination, and imagePublicEmbedBaseUrl. Use
fetchBlogPostBySlug / fetchBlogPostJsonLd only when calling the
same-origin BFF from the browser or another same-origin path.
setReaction / setFeedback always POST without ISR cache.
Components
import {
BlogArticleBody,
BlogLinkedLinksDisplay,
BlogPrintableButtons,
BlogArticleMarks,
BlogArticleShare,
} from '@mailoo/blog/client'BlogArticleMarks POSTs to same-origin BFF (/api/v1/blog/slug/.../reaction|feedback),
shows public counts, and stores visitor state in localStorage. Pass i18n labels
from the host.
BlogArticleShare renders X / Facebook / LinkedIn / copy-link controls. Pass
interpolated text, i18n labels, and optional absolute url (when omitted,
clicks use origin + pathname). Subpath: @mailoo/blog/client/share.
Host app owns locale routing, i18n strings, theme, and page layouts.
BlogPrintableButtons adds a print button to each [data-mailoo-print]
section. printLabel and buttonClassName are optional. containerSelector
limits enhancement to one root; if that root is missing, no buttons are added.
Omit it to enhance the whole document. onPrint({ section, printTitle }) runs
before the print window opens — the package does not call analytics.
sourceLabel (host i18n) appends a source block: the label, document.title,
and the page URL. The print window opens with window.open('', '_blank')
(no noopener), then sets opener to null, and calls print() once.
Host: errors must not take down the app
createMailooBlogClient methods return { ok: false, status } on network /
upstream failure — they never throw. Check ok before rendering. Prefer
feature-local error UI over crashing the page. Do not call the blog client
from root layout.tsx. Article pages: use notFound() only for HTTP 404;
other failures should show an in-page error (HTTP 200).
