Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(nextjs-blog): merge into existing blogs

Yuting Zhong92083f827aa9
diff --git a/notfair-nextjs-blog/README.md b/notfair-nextjs-blog/README.md
index 861b4ec2..47f4833c 100644
--- a/notfair-nextjs-blog/README.md
+++ b/notfair-nextjs-blog/README.md
@@ -21,9 +21,9 @@ npm install notfair-nextjs-blog
NOTFAIR_SEO_API_KEY=nfbl_...
```
-4. Set your integration's **public post URL pattern** to where these pages
- render (e.g. `https://yoursite.com/blog/{slug}`) — link verification crawls
- it, and hosted links only earn credits once verified.
+4. Publish NotFair posts under `/blog/{slug}`. The dashboard derives the
+ verification URL automatically. If `/blog` already exists, merge NotFair
+ into it as an additional source rather than replacing the route.
## Minimal app/blog
@@ -73,7 +73,56 @@ export default async function BlogPost({
Responses revalidate hourly by default (`{ revalidate }` option to change).
+## Existing `/blog`
+
+Keep your current blog queries, components, metadata, and styling. Native posts
+win slug collisions; NotFair fills only the remaining index entries and slugs.
+
+For the index, fetch both sources in parallel and merge them without reshaping
+your existing post type:
+
+```tsx
+import { getSeoPosts, mergeBlogPosts } from "notfair-nextjs-blog";
+
+const [existingPosts, seoPosts] = await Promise.all([
+ getExistingPosts(),
+ getSeoPosts(),
+]);
+const posts = mergeBlogPosts(existingPosts, seoPosts);
+
+// Branch on item.source and render each source with the site's existing cards.
+// Every item still links to /blog/${item.post.slug}.
+```
+
+For `app/blog/[slug]/page.tsx`, resolve the existing source first and call
+NotFair only as a fallback:
+
+```tsx
+import { notFound } from "next/navigation";
+import { getBlogPostWithSeoFallback } from "notfair-nextjs-blog";
+
+const result = await getBlogPostWithSeoFallback(slug, getExistingPost);
+if (!result) notFound();
+
+if (result.source === "existing") {
+ return <ExistingPost post={result.post} />;
+}
+
+return (
+ <article>
+ <h1>{result.post.title}</h1>
+ <div dangerouslySetInnerHTML={{ __html: result.post.content_html }} />
+ </article>
+);
+```
+
+Apply the same native-first lookup in `generateMetadata`. Do not call
+`notFound()` until both sources return no post.
+
## API
- `getSeoPosts({ revalidate? })` → `[{ id, title, slug, published_at, created_at }]`
- `getSeoPost(slug, { revalidate? })` → adds `content_html`, or `null`
+- `mergeBlogPosts(existing, seo)` → discriminated list; existing slugs win
+- `getBlogPostWithSeoFallback(slug, getExistingPost, { revalidate? })` →
+ `{ source, post }`, or `null`
diff --git a/notfair-nextjs-blog/package.json b/notfair-nextjs-blog/package.json
index a19f73f1..f6e63ecc 100644
--- a/notfair-nextjs-blog/package.json
+++ b/notfair-nextjs-blog/package.json
@@ -1,6 +1,6 @@
{
"name": "notfair-nextjs-blog",
- "version": "0.2.0",
+ "version": "0.3.0",
"description": "Render your NotFair SEO exchange posts on a Next.js blog — server-side content pulls with your private site API key.",
"license": "MIT",
"type": "module",
@@ -19,6 +19,7 @@
],
"scripts": {
"build": "tsc -p tsconfig.json",
+ "test": "npm run build && node --test test/*.test.mjs",
"prepublishOnly": "tsc -p tsconfig.json"
},
"keywords": [
diff --git a/notfair-nextjs-blog/src/index.ts b/notfair-nextjs-blog/src/index.ts
index d3ff43a8..b6f08bd6 100644
--- a/notfair-nextjs-blog/src/index.ts
+++ b/notfair-nextjs-blog/src/index.ts
@@ -24,6 +24,33 @@ export type SeoPostSummary = {
export type SeoPost = SeoPostSummary & { content_html: string };
+export type SeoFetchOptions = { revalidate?: number };
+
+/** A collision-safe union for rendering an existing blog index alongside
+ * NotFair posts without forcing either source into the other's data shape. */
+export type MergedBlogPost<T> =
+ | { source: "existing"; post: T }
+ | { source: "notfair"; post: SeoPostSummary };
+
+/** Merge NotFair summaries into an existing blog. Existing posts keep their
+ * order and win duplicate slugs; NotFair-only posts follow in API order. */
+export function mergeBlogPosts<T extends { slug: string }>(
+ existingPosts: readonly T[],
+ seoPosts: readonly SeoPostSummary[],
+): MergedBlogPost<T>[] {
+ const existingSlugs = new Set(existingPosts.map((post) => post.slug));
+ return [
+ ...existingPosts.map((post) => ({ source: "existing" as const, post })),
+ ...seoPosts
+ .filter((post) => !existingSlugs.has(post.slug))
+ .map((post) => ({ source: "notfair" as const, post })),
+ ];
+}
+
+export type ResolvedBlogPost<T> =
+ | { source: "existing"; post: T }
+ | { source: "notfair"; post: SeoPost };
+
function apiKey(): string {
const key = process.env.NOTFAIR_SEO_API_KEY;
if (!key) {
@@ -49,7 +76,7 @@ async function contentFetch(path: string, revalidate: number): Promise<Response>
/** List published exchange posts (no bodies — cheap for blog indexes). */
export async function getSeoPosts(
- opts: { revalidate?: number } = {},
+ opts: SeoFetchOptions = {},
): Promise<SeoPostSummary[]> {
const res = await contentFetch("", opts.revalidate ?? 3600);
if (!res.ok) return [];
@@ -61,10 +88,25 @@ export async function getSeoPosts(
* slug doesn't exist or isn't published. */
export async function getSeoPost(
slug: string,
- opts: { revalidate?: number } = {},
+ opts: SeoFetchOptions = {},
): Promise<SeoPost | null> {
const res = await contentFetch(`?slug=${encodeURIComponent(slug)}`, opts.revalidate ?? 3600);
if (!res.ok) return null;
const body = (await res.json().catch(() => null)) as { post?: SeoPost } | null;
return body?.post ?? null;
}
+
+/** Resolve a dynamic /blog/[slug] route without shadowing the site's native
+ * posts. The existing loader always runs first; NotFair is queried only when
+ * it returns null or undefined. */
+export async function getBlogPostWithSeoFallback<T>(
+ slug: string,
+ getExistingPost: (slug: string) => T | null | undefined | Promise<T | null | undefined>,
+ opts: SeoFetchOptions = {},
+): Promise<ResolvedBlogPost<T> | null> {
+ const existing = await getExistingPost(slug);
+ if (existing != null) return { source: "existing", post: existing };
+
+ const post = await getSeoPost(slug, opts);
+ return post ? { source: "notfair", post } : null;
+}
diff --git a/notfair-nextjs-blog/test/merge.test.mjs b/notfair-nextjs-blog/test/merge.test.mjs
new file mode 100644
index 00000000..44735a7f
--- /dev/null
+++ b/notfair-nextjs-blog/test/merge.test.mjs
@@ -0,0 +1,64 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ getBlogPostWithSeoFallback,
+ mergeBlogPosts,
+} from "../dist/index.js";
+
+const seoPost = {
+ id: 1,
+ title: "NotFair post",
+ slug: "shared-slug",
+ meta_description: null,
+ tags: [],
+ image_url: "https://example.com/image.png",
+ reading_time_minutes: 2,
+ published_at: null,
+ created_at: "2026-08-09T00:00:00.000Z",
+};
+
+test("mergeBlogPosts preserves native posts on slug collisions", () => {
+ const existing = [{ slug: "shared-slug", title: "Native post" }];
+ const seoOnly = { ...seoPost, id: 2, slug: "seo-only" };
+
+ assert.deepEqual(mergeBlogPosts(existing, [seoPost, seoOnly]), [
+ { source: "existing", post: existing[0] },
+ { source: "notfair", post: seoOnly },
+ ]);
+});
+
+test("getBlogPostWithSeoFallback does not fetch NotFair when a native post exists", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async () => {
+ throw new Error("NotFair should not be fetched");
+ };
+
+ try {
+ const native = { slug: "native", title: "Native post" };
+ const result = await getBlogPostWithSeoFallback("native", async () => native);
+ assert.deepEqual(result, { source: "existing", post: native });
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("getBlogPostWithSeoFallback returns a NotFair post after a native miss", async () => {
+ const originalFetch = globalThis.fetch;
+ const originalKey = process.env.NOTFAIR_SEO_API_KEY;
+ process.env.NOTFAIR_SEO_API_KEY = "nfbl_test";
+ globalThis.fetch = async () =>
+ new Response(JSON.stringify({ post: { ...seoPost, content_html: "<p>Body</p>" } }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+
+ try {
+ const result = await getBlogPostWithSeoFallback("shared-slug", async () => null);
+ assert.equal(result?.source, "notfair");
+ assert.equal(result?.post.slug, "shared-slug");
+ } finally {
+ globalThis.fetch = originalFetch;
+ if (originalKey === undefined) delete process.env.NOTFAIR_SEO_API_KEY;
+ else process.env.NOTFAIR_SEO_API_KEY = originalKey;
+ }
+});