@sitefabric/next

@sitefabric/next SDK Guide

@sitefabric/next is the official, self-contained Next.js 15 App Router SDK for websites built on SiteFabric. Instead of wiring separate HTTP clients for SEO, CMS content, lead forms, cache invalidation, and redirects, you configure defineSiteFabric() once and get strongly typed Server Components, route handlers, and Edge-runtime middleware out of the box.

1. Installation & Environment Variables

Install @sitefabric/next in any Next.js 15+ / React 19+ project (projects scaffolded with sitefabric create project already have this installed and wired automatically):

Install via npmbash
npm install @sitefabric/next

Because all SiteFabric data endpoints require strict Bearer authentication, store your sf_tok_... token in server-only environment variables (.env.local) so it is never bundled into browser JavaScript:

VariableRuntimePurpose
SITEFABRIC_PROJECT_IDServerWebsite Project ID from SiteFabric CRM.
SITEFABRIC_WEBSITE_KEYServer / EdgeWebsite slug key (e.g. acme).
SITEFABRIC_API_URLServer / EdgeSiteFabric API origin URL.
SITEFABRIC_API_TOKENServer / Edge (Secret)Personal or project-scoped sf_tok_... token. Never expose with NEXT_PUBLIC_.
SITEFABRIC_CANONICAL_DOMAINServerPrimary domain (e.g. acme.com).
SITEFABRIC_REVALIDATION_SECRETServer (Secret)HMAC-SHA256 secret for /api/revalidate.

2. Central Configuration (defineSiteFabric)

Create a single shared instance in lib/sitefabric.ts and import it across your layouts, pages, and route handlers. When revalidateSeconds is omitted, the SDK automatically disables caching in local development (0s) so any edit you make in SiteFabric CRM appears immediately on refresh, while using 60s tagged ISR caching in production paired with instant webhook revalidation.

lib/sitefabric.tstypescript
import { defineSiteFabric } from '@sitefabric/next';

export const sitefabric = defineSiteFabric({
  projectId: process.env.SITEFABRIC_PROJECT_ID,
  websiteKey: process.env.SITEFABRIC_WEBSITE_KEY!,
  apiBaseUrl: process.env.SITEFABRIC_API_URL!,
  apiToken: process.env.SITEFABRIC_API_TOKEN!,
  canonicalDomain: process.env.SITEFABRIC_CANONICAL_DOMAIN!,
  siteName: 'Acme Website',
  revalidationSecret: process.env.SITEFABRIC_REVALIDATION_SECRET,
  staticRoutes: ['/', '/about', '/contact'],
  defaultLocale: 'en',
});
OptionTypeDescription
websiteKey*stringUnique website slug registered in SiteFabric CRM (e.g. "acme").
apiBaseUrl*stringBase URL of your SiteFabric API server (e.g. https://api.sitefabric.space).
apiToken*stringBearer auth token (sf_tok_...) used to authenticate server-side and Edge requests. Defaults to process.env.SITEFABRIC_API_TOKEN.
canonicalDomain*stringPrimary production hostname used to build canonical URLs, sitemaps, and OpenGraph links.
projectIdstringMongoDB ObjectId of the website in SiteFabric CRM (populated automatically by the CLI).
revalidationSecretstringShared secret used to verify HMAC-SHA256 on-demand revalidation webhooks from CRM.
staticRoutesstring[]Fallback static routes merged into sitemap.xml alongside published CMS pages.
defaultLocalestringDefault content locale (defaults to "en").
revalidateSecondsnumberNext.js fetch cache TTL. Automatically defaults to 0 in development (instant CRM edits on refresh) and 60 in production.

3. SEO Metadata, JSON-LD & CMS Content

Every page can pull live SEO metadata via sitefabric.seo.getMetadata() (with safe local fallbacks if a route has not been customized in CRM yet), inject sanitized Schema.org structured data via <JsonLdScript /> (which strips any <script> injection sequences automatically), and render structured CMS blocks via <CmsBlockRenderer />:

  • sitefabric.seo.getMetadata(path, fallback) — returns a Next.js Metadata object with title, description, canonical URL, robots, OpenGraph, and Twitter tags.
  • sitefabric.seo.sitemap() & sitefabric.seo.robots() — drop directly into app/sitemap.ts and app/robots.ts.
  • sitefabric.cms.getPage(slug, { locale, previewToken }) — fetches a published page (or an unpublished draft when a signed preview token is provided).
  • sitefabric.cms.getCollection(key) & sitefabric.cms.getNavigation(key) — load structured collections (services, FAQs, team) and header/footer menus.
app/page.tsxtsx
import { CmsBlockRenderer, JsonLdScript } from '@sitefabric/next';
import { sitefabric } from '@/lib/sitefabric';

export async function generateMetadata() {
  return sitefabric.seo.getMetadata('/', {
    title: 'Acme Website',
    description: 'Modern services powered by SiteFabric.',
  });
}

export default async function HomePage() {
  const page = await sitefabric.cms.getPage('home');
  return (
    <main>
      <JsonLdScript plugin={sitefabric.seo} path="/" />
      <CmsBlockRenderer blocks={page?.blocks ?? []} />
    </main>
  );
}

4. Instant On-Demand Cache Revalidation

Whenever an editor publishes a page, updates SEO metadata, or changes a redirect in SiteFabric CRM, the API sends an HMAC-SHA256 signed POST request to your website's /api/revalidate route. Wire the built-in handler once and production pages update within milliseconds without rebuilding:

app/api/revalidate/route.tstypescript
import { sitefabric } from '@/lib/sitefabric';

export async function POST(request: Request): Promise<Response> {
  return sitefabric.revalidateHandler(request);
}

5. Edge Middleware (Redirects & Maintenance Mode)

Import middleware from the dedicated @sitefabric/next/middleware subpath. It contains zero node:* imports so it runs natively on the Next.js Edge Runtime. On incoming requests, it fetches and caches your website's live runtime bundle (/api/v1/public/websites/:key/seo/runtime) to:

  • Execute live 301, 302, 307, and 308 redirect rules configured in SiteFabric CRM without redeploying your website.
  • Return a clean branded HTTP 503 Service Unavailable page automatically when Maintenance Mode is toggled on in SiteFabric CRM.
  • Fail-open resilience: if the API is temporarily unreachable, middleware falls through to NextResponse.next() so your public site stays online.
middleware.tstypescript
import { createSiteFabricMiddleware } from '@sitefabric/next/middleware';

export const middleware = createSiteFabricMiddleware({
  websiteKey: process.env.SITEFABRIC_WEBSITE_KEY!,
  apiBaseUrl: process.env.SITEFABRIC_API_URL!,
  apiToken: process.env.SITEFABRIC_API_TOKEN!,
});

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)'],
};