Skip to main content

SSR SDK

For server-rendered frameworks, NxisAI provides the NxisClient class. It fetches your JSON-LD at render time so structured data is present in the initial HTML response — no client-side JavaScript required.

Why SSR matters

Search engines can render JavaScript, but LLMs and AI agents often don't execute JS when crawling. If your structured data is only injected client-side, agents may never see it. SSR embeds JSON-LD directly in the initial HTML, making it visible to every consumer — search crawlers, LLM pipelines, and AI agents browsing on a user's behalf.

Installation​

npm install @nxisai/sdk

@nxisai/sdk is for servers only (SSR, SSG, Node.js). Browser-side injection is done by the JS tag, which isn't an npm package.

Upgrading from @nxisai/nxis?

Up to version 2.x, this SDK was published as @nxisai/nxis. From 3.0.0 it's @nxisai/sdk, with the same NxisClient API. See Migrating to @nxisai/sdk.

Authentication​

The SSR client uses OAuth 2.0 client credentials. Access tokens are obtained and refreshed automatically — see Token lifecycle. Create your credentials on the API Keys page and provide them as environment variables:

NXIS_API_HOST=https://api.nxis.ai
NXIS_CLIENT_ID=... # your OAuth client ID
NXIS_CLIENT_SECRET=... # your OAuth client secret
NXIS_SITE_ID=... # your site identifier
warning

Keep your client secret on the server. Never expose it in client-side code or commit it to source control.

API reference​

import { NxisClient } from '@nxisai/sdk';

const nxis = new NxisClient({
clientId: string, // OAuth client ID
clientSecret: string, // OAuth client secret
tokenUrl?: string, // optional token endpoint URL (defaults to NXIS_TOKEN_URL env var)
scope?: string, // optional OAuth scope (defaults to "jsonld:read")
apiHost?: string, // optional API host override (defaults to NXIS_API_HOST env var)
});

const jsonLd: Record<string, unknown> = await nxis.getStructuredData({
uri: string, // the full URI of the page being rendered
siteId: string, // the site identifier
userAgent?: string, // optional User-Agent for bot detection
});

getStructuredData returns a Promise<Record<string, unknown>> — a JSON-LD object ready to serialize into a <script type="application/ld+json"> tag.

Token lifecycle​

Access tokens are managed automatically by NxisClient:

  • Lazy initialization — no token is fetched until the first getStructuredData call.
  • In-memory cache — tokens are cached and reused for subsequent requests.
  • Auto-refresh — tokens are refreshed 60 seconds before expiration.
  • Concurrency-safe — multiple concurrent requests during a refresh all await the same token fetch.

Errors​

getStructuredData throws one of two error types:

ErrorWhenWhat to do
NxisWarningThe request succeeded, but there's no structured data for this page.Not fatal. Render the page without JSON-LD.
ProxyErrorAnything else: authentication, permissions, rate limits, server errors.Carries code (a gRPC-style ErrorCode), httpStatus, and the helpers isRetryable (rate limited or internal error) and isAuthError (unauthenticated or permission denied).
import { NxisClient, NxisWarning, ProxyError } from '@nxisai/sdk';

let jsonLd: Record<string, unknown> | undefined;
try {
jsonLd = await nxis.getStructuredData({ uri, siteId });
} catch (e) {
if (e instanceof NxisWarning) {
jsonLd = undefined; // no data for this page: render without it
} else if (e instanceof ProxyError && e.isAuthError) {
console.error('Check NXIS_CLIENT_ID / NXIS_CLIENT_SECRET', e.httpStatus);
} else {
throw e;
}
}

The package also exports ErrorCode, errorCodeToHttp, and these types: NxisClientConfig, NxisSSRRequest, StructuredDataResponse, NxisErrorResponse, NxisConfig and NxisIndexConfig.


Framework examples​

Next.js (App Router)​

// app/page.tsx
import { NxisClient } from '@nxisai/sdk';
import { headers } from 'next/headers';

const nxis = new NxisClient({
clientId: process.env.NXIS_CLIENT_ID!,
clientSecret: process.env.NXIS_CLIENT_SECRET!,
});

export default async function Page() {
const headersList = await headers();
const host = headersList.get('host') ?? 'localhost:3000';
const proto = headersList.get('x-forwarded-proto') ?? 'http';
const pageUri = `${proto}://${host}/`;

const jsonLd = await nxis.getStructuredData({
uri: pageUri,
siteId: process.env.NXIS_SITE_ID!,
userAgent: headersList.get('user-agent') ?? undefined,
});

return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<main>{/* page content */}</main>
</>
);
}

Next.js (Pages Router)​

// pages/index.tsx
import { NxisClient } from '@nxisai/sdk';
import Head from 'next/head';
import { GetServerSideProps } from 'next';

const nxis = new NxisClient({
clientId: process.env.NXIS_CLIENT_ID!,
clientSecret: process.env.NXIS_CLIENT_SECRET!,
});

export const getServerSideProps: GetServerSideProps = async (context) => {
const jsonLd = await nxis.getStructuredData({
uri: `https://yoursite.com${context.resolvedUrl}`,
siteId: process.env.NXIS_SITE_ID!,
});

return { props: { jsonLd } };
};

export default function Page({ jsonLd }: { jsonLd: Record<string, unknown> }) {
return (
<>
<Head>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
</Head>
<main>{/* page content */}</main>
</>
);
}

Nuxt 3​

<!-- pages/index.vue -->
<script setup lang="ts">
import { NxisClient } from '@nxisai/sdk';

const config = useRuntimeConfig();
const nxis = new NxisClient({
clientId: config.nxisClientId,
clientSecret: config.nxisClientSecret,
});

const { data: jsonLd } = await useAsyncData('nxis-jsonld', () =>
nxis.getStructuredData({
uri: `https://yoursite.com${useRoute().fullPath}`,
siteId: config.nxisSiteId,
})
);

useHead({
script: [
{
type: 'application/ld+json',
innerHTML: JSON.stringify(jsonLd.value),
},
],
});
</script>

<template>
<main><!-- page content --></main>
</template>

Remix​

// app/routes/_index.tsx
import { json, type LoaderFunctionArgs } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { NxisClient } from '@nxisai/sdk';

const nxis = new NxisClient({
clientId: process.env.NXIS_CLIENT_ID!,
clientSecret: process.env.NXIS_CLIENT_SECRET!,
});

export async function loader({ request }: LoaderFunctionArgs) {
const jsonLd = await nxis.getStructuredData({
uri: request.url,
siteId: process.env.NXIS_SITE_ID!,
});

return json({ jsonLd });
}

export default function Index() {
const { jsonLd } = useLoaderData<typeof loader>();

return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<main>{/* page content */}</main>
</>
);
}

Astro​

---
// src/pages/index.astro
import { NxisClient } from '@nxisai/sdk';

const nxis = new NxisClient({
clientId: import.meta.env.NXIS_CLIENT_ID,
clientSecret: import.meta.env.NXIS_CLIENT_SECRET,
});

const jsonLd = await nxis.getStructuredData({
uri: Astro.url.href,
siteId: import.meta.env.NXIS_SITE_ID,
});
---

<html>
<head>
<script type="application/ld+json" set:html={JSON.stringify(jsonLd)} />
</head>
<body>
<!-- page content -->
</body>
</html>

SvelteKit​

// src/routes/+page.server.ts
import { NxisClient } from '@nxisai/sdk';
import { env } from '$env/static/private';
import type { PageServerLoad } from './$types';

const nxis = new NxisClient({
clientId: env.NXIS_CLIENT_ID,
clientSecret: env.NXIS_CLIENT_SECRET,
});

export const load: PageServerLoad = async ({ url }) => {
const jsonLd = await nxis.getStructuredData({
uri: url.href,
siteId: env.NXIS_SITE_ID,
});

return { jsonLd };
};
<!-- src/routes/+page.svelte -->
<script lang="ts">
export let data;
</script>

<svelte:head>
{@html `<script type="application/ld+json">${JSON.stringify(data.jsonLd)}</script>`}
</svelte:head>

<main><!-- page content --></main>

Express / Node.js​

const express = require('express');
const { NxisClient } = require('@nxisai/sdk');

const nxis = new NxisClient({
clientId: process.env.NXIS_CLIENT_ID,
clientSecret: process.env.NXIS_CLIENT_SECRET,
});

const app = express();

app.get('*', async (req, res) => {
const jsonLd = await nxis.getStructuredData({
uri: `https://yoursite.com${req.originalUrl}`,
siteId: process.env.NXIS_SITE_ID,
});

res.send(`
<!DOCTYPE html>
<html>
<head>
<script type="application/ld+json">${JSON.stringify(jsonLd)}</script>
</head>
<body><!-- page content --></body>
</html>
`);
});

app.listen(3000);

Add it with Claude Code​

You can use Claude Code to add NxisAI SSR to an existing Next.js project automatically. Paste this prompt from your project root:

Install the @nxisai/sdk package and add server-side structured data injection to my
Next.js App Router project. Here's what I need:

1. Install the @nxisai/sdk npm package
2. Add NXIS_API_HOST, NXIS_CLIENT_ID, and NXIS_CLIENT_SECRET to my .env.local
3. Create a shared NxisClient instance using `NxisClient` from `@nxisai/sdk`
initialized with the OAuth client credentials from environment variables
4. Update my root layout (or individual pages) to:
- Import `headers` from `next/headers`
- Derive the page URI from the incoming request's `host` and `x-forwarded-proto` headers
- Pass the `user-agent` header for bot detection
- Inject the returned JSON-LD as a <script type="application/ld+json"> tag

Make sure JSON-LD is present in the initial HTML response so it's visible to search
engines, LLMs, and AI agents that don't render JavaScript.

Supported frameworks​

FrameworkRenderingMethod
Static HTML / WordPress / ShopifyClient-side<script> tag
Next.js (App & Pages Router)SSR / SSGNxisClient
Nuxt 3SSR / SSGNxisClient
RemixSSRNxisClient
AstroSSR / SSGNxisClient
SvelteKitSSR / SSGNxisClient
Express / Node.jsServerNxisClient