npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@rankworks/next-seo

v0.3.0

Published

Next.js SDK for RankWorks SEO platform — fetch content, apply SEO metadata, and validate webhooks

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-seo

Then 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 pagination
  • getPostSEO({ slug }) — Get SEO metadata for a post
  • getSEO({ url, title?, content?, excerpt? }) — Evaluate SEO for any page URL

SEO & Structured Data

  • toNextMetadata(seo) — Convert SEO response to Next.js App Router Metadata
  • toHeadProps(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 generation
  • toNextSitemap(response, defaults?) — Convert a SitemapResponse to MetadataRoute.Sitemap format (see Sitemap Helper)
  • getRedirects() — Get configured redirects
  • withRankWorksRedirects(client) — Returns a function compatible with next.config.mjs redirects
  • toNextRedirects(redirects) — Transform redirect data to Next.js format

Tracking & Webhooks

  • <RankWorksScript code? domain? src? nonce? /> — Inject the RankWorks analytics script
  • getScriptConfig() — Fetch tracking script configuration
  • revalidateHandler(options) — Factory for a revalidation webhook Route Handler
  • verifyWebhookSignature(headers, body, secret, options?) — Verify a webhook signature (async, returns Promise<boolean>)
  • parseWebhookEvent(headers, body, secret, options?) — Verify + parse into a typed RankWorksWebhookEvent (async)

Analytics & Insights

  • getBusinessProfile() — Fetch Google Business Profile data
  • getReviews({ limit? }) — Fetch recent reviews with summary stats
  • getKeywordRankings({ domain?, limit? }) — Fetch tracked keyword positions and trends
  • getPageAnalytics({ path?, limit? }) — Fetch page-level GA4 metrics
  • getContentScore({ url?, title?, content? }) — Get SEO content quality score (0–100)
  • getInternalLinks({ content, topic?, title?, website?, maxLinks? }) — Enhance content with internal links
  • getImageAudit(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_SECRET in your Next.js environment to that same value. The handler calls verifyWebhookSignature on every inbound request using X-RankWorks-Signature + X-RankWorks-Timestamp headers before invoking onDeploy, 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: verifyWebhookSignature is now async and returns Promise<boolean>. Any code that called it synchronously must be updated to await the result. The revalidateHandler, pagesRouterRevalidateHandler, withRankWorksDeployHook, and pagesRouterDeployHookHandler factories 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