Published on

No Datasource, No Problem: A Server-Safe withDatasourceCheck for SitecoreAI

Authors

Every JSS-era component we've written is wrapped in withDatasourceCheck. It's the higher-order component (HOC) that shows authors a "pick a datasource" message in Pages and renders nothing on the live site when a rendering has no datasource. So when our reference sample component on a new SitecoreAI App Router build turned up with no datasource check at all, the obvious question was: why not here?

Verified on Sitecore Content SDK 2.5.1, Next.js 16.4 (App Router), React 19 and next-intl 4.

What withDatasourceCheck Does

Trimmed of comments, the SDK's HOC (@sitecore-content-sdk/react 2.5.0, re-exported from @sitecore-content-sdk/nextjs) looks like this:

'use client';
import React from 'react';
import { useSitecore } from './../components/SitecoreProvider';

export const DefaultEditingError = () => (
  <div className="sc-jss-editing-error" role="alert">
    Datasource is required. Please choose a content item for this component.
  </div>
);

function hasValidDatasource(rendering) {
  if (!rendering?.dataSource) return false;
  return rendering.isContentResolved !== false;
}

export function withDatasourceCheck(options) {
  return function withDatasourceCheckHoc(Component) {
    return (props) => {
      const { page } = useSitecore();
      const EditingError = options?.editingErrorComponent ?? DefaultEditingError;
      const isDesignLibrary = page.mode.isDesignLibrary;
      return isDesignLibrary || hasValidDatasource(props.rendering)
        ? <Component {...props} />
        : page.mode.isEditing ? <EditingError /> : null;
    };
  };
}
  • Missing means rendering.dataSource is empty, or rendering.isContentResolved === false, which the SDK types describe as resolution failing "for example because the item was deleted or archived". An absent isContentResolved counts as resolved.
  • The Design Library skips the check, so a component can be previewed there without a datasource.
  • Live mode renders null; editing renders the error component, which you can swap with options.editingErrorComponent.

Why It Can't Wrap a Server Component

The file starts with 'use client' and the HOC calls useSitecore(), a React context hook. Server Components can't use context, and in a Content SDK App Router app every rendering is a Server Component unless its file says otherwise. So the SDK HOC only fits the minority of renderings that are already client components.

It's also exported from @sitecore-content-sdk/nextjs, the same package every rendering imports Text, Link and Image from. Auto-import will happily hand it to you, and TypeScript doesn't model the server/client boundary, so nothing complains until the page runs. Let's see what that looks like. One Server Component rendering, exported through the SDK HOC:

import { withDatasourceCheck } from '@sitecore-content-sdk/nextjs';
export default withDatasourceCheck()(DatasourceWithChildren);

next dev, request the test page:

○ Compiling /[site]/[locale]/[[...path]] ...
⨯ Error: Attempted to call withDatasourceCheck() from the server but withDatasourceCheck is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.
    at module evaluation (src\components\samples\datasource-with-children\DatasourceWithChildren.tsx:67:35)
    at module evaluation (.sitecore\component-map.ts:9:1)
> 67 | export default withDatasourceCheck()(DatasourceWithChildren);
     |                                   ^
 GET /<test-page> 500 in 6.9s
  • Why that message. Because the SDK file is 'use client', withDatasourceCheck on the server isn't the function. It's a client reference, which the server can render or pass as a prop, but can't call. withDatasourceCheck() calls it.
  • It fails at module evaluation, not at render. Look at the second stack frame: the module is loaded by .sitecore/component-map.ts, the generated map that statically imports every rendering.
  • So one rendering takes down every page. The catch-all route imports the component map. The home page, which doesn't even contain this rendering, returned the same 500. One wrong import on one component, and the whole site is down.

We're not the first to hit this. Content SDK issue #361 was reported in February on Content SDK 1.4.0, when the HOC had no 'use client' and the error named useSitecore() instead. A Sitecore maintainer called it "semi-expected" in the App Router: page wasn't passed across the server/client boundary, so the HOC read it from context, and 2.0 added 'use client' "to avoid unpleasant surprises". Their suggestion for React Server Components was an explicit check on props.rendering. A follow-up comment pointed out that page is now passed to every component and asked for the HOC to be re-evaluated. The issue is still open at the time of writing, and we added our findings to it.

Our 2.5.1 data backs that follow-up up. Server renderings get page as a prop from AppPlaceholder, and client renderings get it from ClientComponentWrapper, which reads useSitecore() on the client side and adds page to the rendering's props. A hook-free HOC can read everything it needs from props.

Asking an AI, and Checking Its Answer

I asked Gemini for a server-side version. Both drafts were reasonable starting points, and both were wrong in ways worth showing.

Draft 1 (withServerDatasourceCheck) got the big picture right: the SDK HOC is client-only because of useSitecore(), and reading rendering and page from props works in a Server Component. But it skipped the isContentResolved check (a deleted datasource still renders), had no Design Library skip, used sc-jss-empty-placeholder (the SDK's empty-placeholder class, not its editing-error class), and claimed page is stripped from props passed to client components. It isn't:

// @sitecore-content-sdk/react 2.5.0, components/Placeholder/ClientComponentWrapper.js
const { page, componentMap: clientComponentMap } = useSitecore();
const componentPropsWithContext = { ...props.componentProps, rendering: props.rendering, componentMap: clientComponentMap, page };

Draft 2, the "corrected universal" version, fixed the Design Library skip and correctly noted that one hook-free HOC can serve both kinds of rendering. Then this:

const hasDatasource = Boolean(rendering?.dataSource || rendering?.isContentResolved);

Every rendering we measured in a preview layout response carries isContentResolved: true, including the one with dataSource: "". So "" || true is true, and the guard never fires for an empty datasource. For a deleted item, "<guid>" || false is also true. The SDK uses &&. One character turns the guard into a no-op that still type-checks and still looks right in review. It also used an sc-jss-empty-rendering class that doesn't exist in the SDK, and reused the name withDatasourceCheck, which collides with the SDK export auto-import loves.

SDK withDatasourceCheckAI draft 1AI draft 2withRequiredDatasource
Wraps a Server ComponentNoYesYesYes
Wraps a Client ComponentYesClaimed no (wrong)YesYes
Empty dataSourceHiddenHiddenNever hiddenHidden
Unresolved itemHiddenNot checkedNever hiddenHidden
Design LibrarySkippedNot handledSkippedSkipped
Editing outputFixed English textFixed English textNon-existent classDictionary phrase

An AI draft is a hypothesis. Check it against the installed package source and a real layout response before it reaches a component.

The Plot Twist: "No Datasource" on Live Edge Isn't null

An Integrated GraphQL rendering (a ComponentQuery on the rendering item) gets its data as fields.data.datasource. With no datasource assigned, here's what a rendering actually receives:

Caserendering.dataSourcefields.data.datasource
Shared datasourceGUID (lowercase, dashed, no braces)the item, with id
Local datasourcethe full item paththe item, with id
No datasource""Preview: null. Live Edge: { id: "11111111111111111111111111111111", <each field>: null, children: { results: [] } }

A guard written as if (!datasource) sees an object on live and carries on, so the published page renders the component's empty <section>, while Pages and preview look perfectly fine. That's the kind of bug that only shows up after someone else publishes.

The good news: rendering.dataSource is "" on preview and live in this case. A wrapper that decides on rendering catches it without ever knowing the magic ID. (Anything that builds cache tags from fields.data IDs should skip the stand-in too, or it tags an item no publish will ever revalidate.) This was measured on Edge runtime mode; I haven't checked snapshot publishing.

The Fix: withRequiredDatasource

// src/lib/component-enhancers/with-required-datasource.tsx
import type { ComponentType, JSX } from 'react';
import { useTranslations } from 'next-intl';
import type { ComponentProps } from 'lib/component-props';

/** Editing-only message from the Dictionary entry `Dictionary/Editing/No Datasource Selected`. */
function NoDatasourceSelected({ site }: { site?: string }): JSX.Element {
  const t = useTranslations(site);
  return (
    <section role="alert" className="min-h-24 rounded-lg border border-dashed border-gray-300 p-4 text-sm text-gray-500">
      {t('NoDatasourceSelected')}
    </section>
  );
}

/** Server-safe form of the SDK's withDatasourceCheck: reads rendering and page from props. */
export function withRequiredDatasource<P extends ComponentProps>(Component: ComponentType<P>) {
  const WithRequiredDatasource = (props: P): JSX.Element | null => {
    const { rendering, page } = props;
    const hasDatasource = !!rendering?.dataSource && rendering.isContentResolved !== false;

    if (hasDatasource || page.mode.isDesignLibrary) {
      return <Component {...props} />;
    }

    return page.mode.isEditing ? <NoDatasourceSelected site={page.siteName} /> : null;
  };

  WithRequiredDatasource.displayName = `withRequiredDatasource(${Component.displayName ?? Component.name})`;
  return WithRequiredDatasource;
}
  • No 'use client', no hooks in the wrapper itself. It runs wherever the rendering runs.
  • Same decision as the SDK: dataSource && isContentResolved !== false, plus the Design Library skip. The Design Library check comes first, because the editable Design Library also sets isEditing.
  • Not curried. withRequiredDatasource(Component), not withDatasourceCheck()(Component). The message comes from the Dictionary, so there's nothing left to configure.
  • Async Server Components work. The wrapper renders <Component {...props} /> rather than calling the component, and React 19's ComponentType accepts an async function component.
  • It lives in src/lib/component-enhancers/, borrowing the SDK's own "enhancers" folder name. In a Content SDK app, every file under src/components/ is auto-registered as a rendering, so shared helpers have to live outside it.

Using it is one line per export, including every variant export the component map registers. A variant you forget to wrap has no guard:

export default withRequiredDatasource(Promo);
// or, with variants:
export const Default = withRequiredDatasource(PromoDefault);
export const Compact = withRequiredDatasource(PromoCompact);

Integrated GraphQL Renderings Keep a Second Check

The wrapper answers "is a datasource assigned and resolvable?". A ComponentQuery can still come back empty (null in preview, the stand-in on live), so those renderings also check the result through a small shared helper rather than a magic string in every component:

// src/lib/datasource.ts
/** Live Edge's stand-in for a ComponentQuery whose datasource is empty. Preview returns null instead. */
const EMPTY_DATASOURCE_ID = '11111111111111111111111111111111';

export function hasDatasource<T extends { id?: string | null }>(item: T | null | undefined): item is T {
  return !!item && (item.id ?? '').replace(/[{}-]/g, '') !== EMPTY_DATASOURCE_ID;
}
const datasource = fields?.data?.datasource;

// withRequiredDatasource already handled "no datasource assigned".
// This catches a query that still returned nothing: null, or live Edge's stand-in item.
if (!hasDatasource(datasource)) {
  return isEditing ? <section className="min-h-24 rounded-lg border border-dashed border-gray-300" /> : null;
}

Select id on the datasource in the ComponentQuery, or hasDatasource() can't see the stand-in.

A Message Authors Can Translate

The SDK's default editing text is hard-coded English. Authors read this message, so it's content, and it belongs in the Dictionary:

  • Item: /sitecore/content/<Site Collection>/<Site>/Dictionary/Editing/No Datasource Selected
  • Key: NoDatasourceSelected
  • Phrase: "No datasource selected. Choose a content item for this component."

The Editing folder is purely organisational. Avoid dots in keys, since next-intl reads a.b as nesting (honestly don't know when this problem started!)

The Content SDK App Router template's src/i18n/request.ts loads the dictionary into next-intl messages under the site name as the namespace, which is why the message component calls useTranslations(page.siteName). It uses the useTranslations hook rather than await getTranslations() on purpose: next-intl supports the hook in non-async Server Components, and it also works inside a client rendering under the NextIntlClientProvider the catch-all page already renders. An async call couldn't run in a client rendering. Serialize the entry with the rest of your Dictionary so every environment gets it.

Bonus: Make the Wrong Import Fail Lint

The SDK import is still one auto-import away, so let's make it an error in the editor with no-restricted-imports:

// eslint.config.mjs (excerpt)
'no-restricted-imports': [
  'error',
  {
    paths: [
      {
        // Client-only (it calls useSitecore()), so it breaks a server rendering at runtime.
        name: '@sitecore-content-sdk/nextjs',
        importNames: ['withDatasourceCheck'],
        message:
          'Use withRequiredDatasource from lib/component-enhancers/with-required-datasource: it works in server and client renderings.',
      },
    ],
  },
],

importNames blocks just this one symbol from a package every rendering imports, and the message names the replacement. The same goes for AI coding agents: our agent rules say to wrap datasource-backed renderings with withRequiredDatasource, and the lint error catches an agent that doesn't listen.

What Not to Wrap

  • Composites that read the page or site, like a global header that reads site settings. They have no datasource on purpose. Wrapped, they'd show "No datasource selected" in Pages and vanish on live.
  • Layout renderings: containers, row and column splitters, partial design dynamic placeholders. Their dataSource is "" by design.

Rule of thumb: wrap a rendering whose rendering item has a Datasource Template, and nothing else. Clearing or deleting the datasource of a wrapped rendering gives the message in Pages and nothing on the published page, and the Design Library still previews it without one, same as the SDK.

In Summary

The SDK's withDatasourceCheck is a client component wearing a server import. Until the SDK ships a server-safe version, a dozen lines you own do the same job in both worlds:

  • Don't use the SDK's withDatasourceCheck on a Server Component: it's 'use client' and calls useSitecore()
  • Wrap every rendering with a Datasource Template, and each variant export, with a props-based wrapper
  • Missing = !rendering.dataSource || rendering.isContentResolved === false. Watch your || vs &&
  • Skip the Design Library; show the message only when page.mode.isEditing
  • Integrated GraphQL: also check the query result, and treat ID 1111… as empty on live Edge
  • Editing message = a Dictionary entry, read with useTranslations(page.siteName)
  • Block the SDK import with no-restricted-imports + importNames
  • Don't wrap composites or layout renderings