@rankworks/next-seo
v0.3.0
Published
Next.js SDK for RankWorks SEO platform — fetch content, apply SEO metadata, and validate webhooks
Maintainers
Readme
@rankworks/next-seo
The official Next.js SDK for RankWorks — everything you need to manage SEO, structured data, analytics, and content optimization in your Next.js app.
Why @rankworks/next-seo?
- Zero-config SEO metadata — Generate meta tags, Open Graph, and canonical URLs from your RankWorks dashboard with a single function call.
- Structured data (JSON-LD) — Render rich snippets for posts and local businesses automatically.
- Webhook revalidation — Keep pages fresh with secure, signature-verified revalidation webhooks.
- Analytics tracking script — Drop in the RankWorks tracking component with automatic deduplication.
- Sitemap generation — Build sitemaps from your published content using Next.js conventions.
- Managed redirects — Sync redirects from RankWorks directly into your
next.config.mjs. - Draft preview mode — Preview unpublished content with token-based authentication.
- Business profile & reviews — Display Google Business Profile data and recent reviews with structured data.
- Keyword rankings — Access tracked keyword positions, search volume, and trend data.
- Page analytics — Pull page-level GA4 metrics to power data-driven features like "Popular Posts."
- Content scoring — Score pages for SEO quality (readability, keyword usage, structure) in CI or at build time.
- Internal link suggestions — Automatically enhance content with relevant internal links.
- Image alt text audit — Find missing or generic alt text across your site with suggested improvements.
Supported Versions
| Next.js | Status | |---------|--------| | 15.x | Fully supported | | 14.2+ | Fully supported | | 14.0–14.1 | Not supported |
App Router is the primary target. Pages Router is supported via toHeadProps.
Quick Start
Install the package and add RANKWORKS_API_KEY to your .env.local:
npm install @rankworks/next-seoThen fetch and apply SEO metadata in any page:
import { createClient, toNextMetadata } from '@rankworks/next-seo';
const client = createClient({ api_key: process.env.RANKWORKS_API_KEY! });
const seo = await client.getPostSEO({ slug: 'my-post' });
export const metadata = toNextMetadata(seo);That's it — your pages now have managed SEO metadata.
Features at a Glance
| Feature | Method / Export |
|---|---|
| SEO metadata (App Router) | toNextMetadata(seo) |
| SEO metadata (Pages Router) | toHeadProps(seo) |
| JSON-LD structured data | <JsonLd data={...} /> |
| Local business structured data | <LocalBusinessJsonLd profile={...} /> |
| Tracking script | <RankWorksScript code={...} domain={...} /> |
| Webhook revalidation | revalidateHandler(options) |
| Typed webhook events | parseWebhookEvent(headers, body, secret) |
| Sitemap entries | toNextSitemap(response, defaults?) |
| Redirects | client.getRedirects() / withRankWorksRedirects(client) |
| Draft preview | client.getPostBySlug(slug, { preview: true, previewToken }) |
| Business profile | client.getBusinessProfile() |
| Reviews | client.getReviews({ limit }) |
| Keyword rankings | client.getKeywordRankings({ domain, limit }) |
| Page analytics | client.getPageAnalytics({ path, limit }) |
| Content scoring | client.getContentScore({ url, title, content }) |
| Internal links | client.getInternalLinks({ content, topic, ... }) |
| Image alt audit | client.getImageAudit(domain) |
Full API Reference
Client
createClient(config) — Create a RankWorks client instance.
| Option | Required | Default | Description |
|---|---|---|---|
| api_key | Yes | — | Your RankWorks API key |
| base_url | No | https://api.rankworks.com | Custom API endpoint (must be *.rankworks.com unless allowCustomBaseUrl is set) |
| timeout | No | 10000 | Request timeout in milliseconds |
| retries | No | 1 | Retry count for GET requests on 5xx errors |
| allowCustomBaseUrl | No | false | Allow non-RankWorks base URLs |
Content Methods
getPostBySlug(slug, options?)— Fetch a published post by slug (pass{ preview, previewToken }for drafts)listPosts(params)— List posts with cursor-based paginationgetPostSEO({ slug })— Get SEO metadata for a postgetSEO({ url, title?, content?, excerpt? })— Evaluate SEO for any page URL
SEO & Structured Data
toNextMetadata(seo)— Convert SEO response to Next.js App RouterMetadatatoHeadProps(seo)— Convert SEO response to Pages Router<Head>props<JsonLd data={...} />— Render JSON-LD structured data<LocalBusinessJsonLd profile={...} type? />— Render LocalBusiness schema.org JSON-LD
Site Management
getSitemapEntries()— Get published URLs with last-modified dates for sitemap generationtoNextSitemap(response, defaults?)— Convert aSitemapResponsetoMetadataRoute.Sitemapformat (see Sitemap Helper)getRedirects()— Get configured redirectswithRankWorksRedirects(client)— Returns a function compatible withnext.config.mjsredirectstoNextRedirects(redirects)— Transform redirect data to Next.js format
Tracking & Webhooks
<RankWorksScript code? domain? src? nonce? />— Inject the RankWorks analytics scriptgetScriptConfig()— Fetch tracking script configurationrevalidateHandler(options)— Factory for a revalidation webhook Route HandlerverifyWebhookSignature(headers, body, secret, options?)— Verify a webhook signature (async, returnsPromise<boolean>)parseWebhookEvent(headers, body, secret, options?)— Verify + parse into a typedRankWorksWebhookEvent(async)
Analytics & Insights
getBusinessProfile()— Fetch Google Business Profile datagetReviews({ limit? })— Fetch recent reviews with summary statsgetKeywordRankings({ domain?, limit? })— Fetch tracked keyword positions and trendsgetPageAnalytics({ path?, limit? })— Fetch page-level GA4 metricsgetContentScore({ url?, title?, content? })— Get SEO content quality score (0–100)getInternalLinks({ content, topic?, title?, website?, maxLinks? })— Enhance content with internal linksgetImageAudit(domain)— Audit images for alt text quality
Error Classes
RankWorksApiError— Thrown on API errors (properties:status,body,url)RankWorksTimeoutError— Thrown on timeouts (properties:url,timeoutMs)
Deploy Hooks
When you publish or unpublish content in RankWorks, the platform can trigger a full site rebuild on Vercel, Netlify, Render, or any other CI/CD platform that exposes a deploy hook URL. There are two ways to set this up:
Mode 1 — Direct (recommended for most teams): Paste your deploy hook URL into the RankWorks dashboard under Next.js Connection → Deploy Hooks. RankWorks calls the hook directly on each publish/unpublish. No code changes needed.
Mode 2 — Via your Next.js API route: Use withRankWorksDeployHook so the hook URL stays private. RankWorks calls your Next.js handler; your handler triggers the rebuild. This keeps the raw deploy hook URL out of RankWorks.
Signing secret: RankWorks signs every deploy-hook POST with the same Webhook Secret you configured in Next.js Connection → Webhook Secret. Set
RANKWORKS_WEBHOOK_SECRETin your Next.js environment to that same value. The handler callsverifyWebhookSignatureon every inbound request usingX-RankWorks-Signature+X-RankWorks-Timestampheaders before invokingonDeploy, so the endpoint is safe to expose publicly.
App Router (Next.js 13+)
// app/api/deploy/route.ts
import { withRankWorksDeployHook } from '@rankworks/next-seo';
export const POST = withRankWorksDeployHook({
// Must match the Webhook Secret in RankWorks → Next.js Connection settings
secret: process.env.RANKWORKS_WEBHOOK_SECRET!,
onDeploy: async () => {
// Trigger your deploy hook (Vercel, Netlify, Render, etc.)
await fetch(process.env.DEPLOY_HOOK_URL!, { method: 'POST' });
},
});Pages Router (Next.js 12+)
// pages/api/deploy.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { pagesRouterDeployHookHandler } from '@rankworks/next-seo';
export const config = { api: { bodyParser: false } };
export default pagesRouterDeployHookHandler({
// Must match the Webhook Secret in RankWorks → Next.js Connection settings
secret: process.env.RANKWORKS_WEBHOOK_SECRET!,
onDeploy: async () => {
await fetch(process.env.DEPLOY_HOOK_URL!, { method: 'POST' });
},
});Point the RankWorks dashboard "Deploy Hook URL" field at https://yoursite.com/api/deploy. RankWorks will sign the request with X-RankWorks-Signature and the handler will verify it before invoking onDeploy.
Edge Runtime Compatibility
All webhook helpers (verifyWebhookSignature, parseWebhookEvent, and the handler factories) use the Web Crypto API (globalThis.crypto.subtle) instead of the Node.js-only crypto module. This means they work in:
- Node.js ≥18 (standard Next.js runtime)
- Vercel Edge Functions and Vercel Edge Middleware
- Cloudflare Workers / Pages Functions
- Fastly Compute@Edge and other V8-isolate runtimes
Breaking change in v0.3.0:
verifyWebhookSignatureis now async and returnsPromise<boolean>. Any code that called it synchronously must be updated toawaitthe result. TherevalidateHandler,pagesRouterRevalidateHandler,withRankWorksDeployHook, andpagesRouterDeployHookHandlerfactories already handle this internally.
To use any webhook handler in an Edge route, add the runtime declaration:
// app/api/deploy/route.ts
export const runtime = "edge"; // ← enables Edge runtime
import { withRankWorksDeployHook } from "@rankworks/next-seo";
export const POST = withRankWorksDeployHook({
secret: process.env.RANKWORKS_WEBHOOK_SECRET!,
onDeploy: async () => {
await fetch(process.env.DEPLOY_HOOK_URL!, { method: "POST" });
},
});Typed Webhook Events
parseWebhookEvent verifies the signature and returns a discriminated-union RankWorksWebhookEvent so TypeScript knows exactly which fields are available on each event type.
// app/api/rankworks-webhook/route.ts
import { parseWebhookEvent } from "@rankworks/next-seo";
import type { RankWorksWebhookEvent } from "@rankworks/next-seo";
export const runtime = "edge"; // optional — works in Node.js too
export async function POST(request: Request) {
const body = await request.text();
const headers: Record<string, string> = {};
request.headers.forEach((v, k) => { headers[k] = v; });
const event = await parseWebhookEvent(
headers,
body,
process.env.RANKWORKS_WEBHOOK_SECRET!,
);
if (!event) {
return new Response("Unauthorized", { status: 401 });
}
switch (event.type) {
case "revalidate":
// event.data.path, event.data.slug, event.data.timestamp — all typed
console.log("Revalidating", event.data.path);
break;
case "deploy":
await fetch(process.env.DEPLOY_HOOK_URL!, { method: "POST" });
break;
case "test":
console.log("Test ping received");
break;
}
return Response.json({ ok: true });
}Event types:
| type | When fired | Typed data fields |
|---|---|---|
| "revalidate" | On post publish / unpublish | path, slug, timestamp |
| "deploy" | When a deploy hook fires | (empty object) |
| "test" | Dashboard "Test" button | (empty object) |
Sitemap Helper
toNextSitemap converts entries from client.getSitemapEntries() into the array format expected by Next.js's app/sitemap.ts. It removes the need to manually map canonical_url → url and updated_at → lastModified. It also accepts a SitemapResponse wrapper object if you have one.
// app/sitemap.ts
import { createClient, toNextSitemap } from "@rankworks/next-seo";
export default async function sitemap() {
const client = createClient({ api_key: process.env.RANKWORKS_API_KEY! });
const entries = await client.getSitemapEntries();
return toNextSitemap(entries, {
changeFrequency: "weekly", // optional — applied to every entry
priority: 0.7, // optional — applied to every entry
});
}Field mapping:
| RankWorks field | Next.js field | Notes |
|---|---|---|
| canonical_url | url | Direct mapping |
| updated_at | lastModified | Converted to Date object |
| (from defaults) | changeFrequency | Optional, applied to all |
| (from defaults) | priority | Optional, applied to all |
The returned array is directly compatible with MetadataRoute.Sitemap from the next package.
Documentation
For detailed usage examples, configuration guides, and integration patterns, see the full documentation.
License
MIT
