Part 3: Creating an empty CMS 13 project
Set up an empty Optimizely CMS 13 project with Opti ID and Optimizely Graph, plus a Next.js front end that reads its start page through the official SDK.
This is where the hands-on work starts. By the end of this part you'll have the two projects from Part 2 running on your machine and talking to each other:
- an empty CMS 13 project, where editors sign in with Opti ID and content syncs to Optimizely Graph;
- a Next.js front end that fetches the CMS start page from Graph through the official Optimizely SDK.
The front end won't render anything pretty yet. It shows the start page as raw JSON. That's on purpose: if the JSON shows up, every connection in the architecture diagram from Part 2 works, and Part 5 can focus on content modeling and rendering instead of plumbing.
It's a long part, because both projects need a few fixes on top of what their scaffolding tools generate. I'll explain each fix as we go, so you know what it's for and what goes wrong without it.
Finished code
The project as it is at the end of this part is on the 003-creating-empty-cms-project branch of the masterclass's example repository, one commit per step. You still need your own keys and the setup steps in the CMS and the Optimizely portals, which aren't in Git.
Before you start
You should have read Part 1 and Part 2. This part uses the stack and folder layout decided in Part 2.
Install these first. The commands in brackets show the version you have:
- .NET 10 SDK (
dotnet --version, should print10.x). - SQL Server 2016 or later, running on your machine or somewhere you can reach. The free Express or Developer edition is fine.
- Node.js 22.23.4 or later (
node --version). The Optimizely SDK refuses older versions. - pnpm (
pnpm --version). If you don't have it, follow the pnpm installation guide.
You also need access to two Optimizely portals:
- the DXP Management Portal (PaaS Portal) for your project, to get the Opti ID and Graph keys for the Integration environment;
- the Opti ID Admin Center (admincenter.optimizely.com), with rights to change product settings, to turn on Opti ID for your CMS instance.
All terminal commands are PowerShell. Every snippet that contains a key or ID uses a placeholder, such as <your-single-key>: replace it with your own value.
Versions used
This part is built and tested on CMS 13.6.0, @optimizely/cms-sdk 3.1.0, @optimizely/cms-create-app 1.1.0 and Next.js 16.4. If something you see doesn't match, check your versions first.
Create the repository
Both projects live in one Git repository, as two plain folders. Create the repository folder first. I'll call it headless-masterclass, but the name is up to you:
mkdir headless-masterclass
cd headless-masterclass
git initInitializing Git now, before anything else, matters for one small reason: create-next-app creates its own Git repository unless it's already inside one, and you don't want a second repository nested in masterclass-web/.
Scaffold the CMS project
Create the solution and the project
Optimizely ships its project templates as a NuGet package. Install it, then create the CMS project and a solution file next to it:
mkdir masterclass-cms
cd masterclass-cms
dotnet new install EPiServer.Templates
dotnet new epi-cms-empty -n HeadlessMasterclass.Web -o HeadlessMasterclass.Web
dotnet new sln -n HeadlessMasterclass
dotnet sln add HeadlessMasterclass.Web\HeadlessMasterclass.Web.csprojepi-cms-empty is the empty CMS template: a working CMS with no content types and no pages. dotnet new sln creates HeadlessMasterclass.slnx, the newer XML solution format that .NET 10 uses by default. You now have this layout:
headless-masterclass/
masterclass-cms/
HeadlessMasterclass.slnx
HeadlessMasterclass.Web/
App_Data/
Properties/launchSettings.json
Resources/
appsettings.json
appsettings.Development.json
HeadlessMasterclass.Web.csproj
nuget.config
Program.cs
Startup.csThe template is built for a different setup from ours. It signs editors in with local ASP.NET Identity accounts and stores the database in a LocalDB file under App_Data. The next steps switch it to Opti ID, add Graph, and point it at SQL Server.
The template also adds a nuget.config that includes Optimizely's own NuGet feed (nuget.optimizely.com). The Optimizely packages aren't on nuget.org, so leave that file where it is.
Swap the packages
Open HeadlessMasterclass.Web\HeadlessMasterclass.Web.csproj and replace the ItemGroup with the package references so it looks like this:
<ItemGroup>
<PackageReference Include="EPiServer.CMS" Version="13.6.0" />
<PackageReference Include="EPiServer.OptimizelyIdentity" Version="13.6.0" />
<PackageReference Include="Optimizely.Graph.Cms" Version="13.6.0" />
</ItemGroup>Here's what changed:
EPiServer.Cms.UI.AspNetIdentityis gone. It provides the local user accounts, which Opti ID replaces.EPiServer.OptimizelyIdentityadds Opti ID. Make sure it's the 13.x version: there's an older 1.x line of the same package for CMS 12.Optimizely.Graph.Cmsadds the Graph integration, the code that syncs content to Graph. Graph is included in the CMS 13 license, but the integration is still a separate package. Don't confuse it withOptimizely.ContentGraph.Cms, which is the CMS 12 package and uses a different version line.- Everything is on 13.6.0. The template I used pinned 13.5.0, yours may pin something else.
Keep all Optimizely packages on exactly the same version, always. They depend on each other's exact versions, so upgrading one on its own fails the restore with an NU1107: Version conflict detected error. When you upgrade later, change all three version numbers together.
Update Startup.cs
Replace the contents of HeadlessMasterclass.Web\Startup.cs with this:
using EPiServer.DependencyInjection;
using EPiServer.Scheduler;
using EPiServer.Web.Routing;
using Optimizely.Graph.DependencyInjection;
namespace HeadlessMasterclass.Web;
public class Startup(IWebHostEnvironment webHostingEnvironment)
{
public void ConfigureServices(IServiceCollection services)
{
if (webHostingEnvironment.IsDevelopment())
{
services.Configure<SchedulerOptions>(options => options.Enabled = false);
}
services.AddOptimizelyIdentity(useAsDefault: true);
services
.AddCms()
.AddContentGraph()
.AddEmbeddedLocalization<Startup>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapContent();
});
}
}Compared with the template:
AddCmsAspNetIdentity<ApplicationUser>()andAddAdminUserRegistration()are gone, along with theirusing. Both belong to the local accounts.AddOptimizelyIdentity(useAsDefault: true)is a separate statement. It returns an authentication builder, not the service collection, so you can't chain.AddCms()after it the way the template chained the old call. If you try, the build fails with errorCS1929.useAsDefault: truemakes Opti ID the sign-in method for the whole application, not only for the CMS editing interface. It needs nousingof its own: the project already imports theEPiServernamespace globally.AddContentGraph()turns on the Graph sync. Unlike the Opti ID call, it does chain. Note itsusing: the package isOptimizely.Graph.Cms, but the namespace isOptimizely.Graph.DependencyInjection. That's an easy one to get wrong.- The
AppDomain.CurrentDomain.SetData("DataDirectory", ...)line is gone. It only exists to make the template's LocalDB file connection string work. We use SQL Server, so it does nothing. The line below it, which turns off scheduled jobs while you develop, stays.
Add the home page content type
An empty CMS has no content types, so there's nothing to create a page from. The front end needs one published page to fetch, so add a single content type for it: the home page. Create the folders Models\Experiences in the project and add HomePageExperience.cs:
using EPiServer.VisualBuilder;
namespace HeadlessMasterclass.Web.Models.Experiences;
[ContentType(
DisplayName = "Home Page Experience",
GUID = "f02b9aee-3d30-40aa-aebd-4f56ec854f93",
Description = "The site's home page, composed with Visual Builder.")]
public class HomePageExperience : ExperienceData
{
}An experience is a page type built for Visual Builder: instead of fixed fields, editors compose the whole page from sections and blocks. This one has no properties at all, and it doesn't need any: Part 5 adds the blocks editors place on it. The GUID identifies the content type in the database. You can keep this one or generate your own with [guid]::NewGuid().
ExperienceData lives in EPiServer.VisualBuilder, which isn't imported globally, so that using is required.
Clean up appsettings.Development.json
Replace the contents of HeadlessMasterclass.Web\appsettings.Development.json with this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"EPiServer": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Optimizely": {
"ContentGraph": {
"GatewayAddress": "https://cg.optimizely.com",
"AllowSendingLogs": false
}
}
}Three things happened here.
The MappedRoles section is gone, and it has to be. The template maps the CmsEditors and CmsAdmins roles for its local accounts. Opti ID maps those roles itself, and Optimizely's Opti ID guide for CMS 13 says you must remove existing mappings for them. In my test project, leaving the section in place stopped the CMS from starting. Every project created from the template has it, so this step isn't optional.
The connection string is gone. It, and every key from the next sections, goes into .NET User Secrets instead, so this file holds no secrets and is safe to commit.
The Graph section has only the non-secret settings. GatewayAddress is Graph's address. AllowSendingLogs controls whether the Graph integration sends its errors and warnings to Optimizely, so that Optimizely support can use them. It's on by default. I turn it off here because this is a tutorial project with no support case behind it. On a real production site, I'd leave it at its default.
CMS 12 settings don't work here
If you've set up Graph on CMS 12, you might reach for AllowSendingLog (singular) or AllowSyncDraftContent. Neither exists in CMS 13, and .NET silently ignores unknown settings, so they do nothing. You don't need a setting for drafts: CMS 13 syncs drafts to Graph by default.
You can also delete the .mdf file in App_Data. It's the template's LocalDB database, which we don't use. Keep the App_Data folder itself: the CMS stores uploaded files there by default.
Prepare the services
The CMS needs a database, Opti ID and Graph before it can start. All three take a few minutes in a browser or a tool, and Opti ID can take a while to become active, so start there.
Turn on Opti ID for your CMS instance
In the Opti ID Admin Center:
- Go to Product Access → Products → Optimizely Content Management System.
- Select your CMS instance. Use a non-production one, such as your Integration environment.
- Open the Details tab and click Edit.
- Check Opti ID Enabled and click Save.
Two things to know before you click Save. You can't uncheck the setting afterwards. And Optimizely says provisioning can take up to an hour. If sign-in fails later with an Opti ID error, this is the first thing to wait for.
Checking the box on its own doesn't change how anyone signs in to that environment. It prepares the instance, and the switch happens when code that uses Opti ID, like ours, runs against it.
Get the Opti ID dev key
In the DXP Management Portal, open your project and go to API → Opti ID dev key. It gives you three values: Instance ID, Client ID and Client Secret. Keep the page open, you'll need them in a moment.
Only keys from the Integration environment work locally.
Opti ID is also strict about where the CMS runs on your machine. Local sign-in only works over HTTPS on one of four addresses: https://localhost:5000, 5096, 6921 or 7595. Open HeadlessMasterclass.Web\Properties\launchSettings.json: the template already sets applicationUrl to https://localhost:5000/, so there's nothing to change. Just don't move it to another port.
Turn on Optimizely Graph
Still in the DXP Management Portal, on the same API tab, find Content Graph Service Configurations and enable the Graph service for the Integration environment. Optimizely's Graph setup guide has the details.
You get three keys:
- App Key and Secret: the CMS uses these to push content to Graph. They can also read drafts, so treat them like a password.
- Single Key: the public, read-only key from Part 2. It only returns published content. The front end uses it.
Create the database
Create an empty database on your SQL Server. With the sqlcmd command-line tool:
sqlcmd -S localhost\SQLEXPRESS -E -C -Q "CREATE DATABASE [HeadlessMasterclass]"localhost\SQLEXPRESS is the default address of a local SQL Server Express. For the Developer edition it's usually just localhost. -E signs in with your Windows account, and -C trusts the server's self-signed certificate. If you prefer SQL Server Management Studio, create an empty database called HeadlessMasterclass there instead.
The database stays empty for now. The CMS creates its tables the first time it starts.
Store the secrets
The CMS now needs seven machine- or account-specific values. .NET User Secrets keeps them in a file in your user profile, outside the repository, and the CMS reads them automatically when it runs in Development mode. Nothing secret ends up in Git.
From the HeadlessMasterclass.Web folder:
cd HeadlessMasterclass.Web
dotnet user-secrets init
dotnet user-secrets set "ConnectionStrings:EPiServerDB" "Server=localhost\SQLEXPRESS;Database=HeadlessMasterclass;Integrated Security=True;TrustServerCertificate=True;Connect Timeout=30"
dotnet user-secrets set "EPiServer:Cms:OptimizelyIdentity:InstanceId" "<your-instance-id>"
dotnet user-secrets set "EPiServer:Cms:OptimizelyIdentity:ClientId" "<your-client-id>"
dotnet user-secrets set "EPiServer:Cms:OptimizelyIdentity:ClientSecret" "<your-client-secret>"
dotnet user-secrets set "Optimizely:ContentGraph:AppKey" "<your-app-key>"
dotnet user-secrets set "Optimizely:ContentGraph:Secret" "<your-secret>"
dotnet user-secrets set "Optimizely:ContentGraph:SingleKey" "<your-single-key>"dotnet user-secrets init adds a UserSecretsId to the .csproj, which links the project to its secrets file. Adjust the Server= part of the connection string if your SQL Server has a different address.
The colons in the key names are how .NET writes nested settings: Optimizely:ContentGraph:AppKey ends up in the same place as the AppKey inside "Optimizely": { "ContentGraph": { ... } } in a JSON file. At runtime, the CMS merges the secrets with appsettings.Development.json.
To check what you've stored, run dotnet user-secrets list. It should show all seven values.
Run the CMS
If you've never run an ASP.NET Core app over HTTPS on this machine, trust the .NET development certificate once, so your browser doesn't warn about it:
dotnet dev-certs https --trustThen start the CMS from the HeadlessMasterclass.Web folder:
dotnet runThe first start takes longer than the next ones, because the CMS creates its tables in the empty database. When the terminal shows Now listening on: https://localhost:5000, open https://localhost:5000/episerver. You should land on the Opti ID sign-in page, not on a local username and password form. Sign in with your Optimizely account, and the CMS editing interface opens.
There's nothing to see at the CMS's own root address. This CMS doesn't render pages, the front end will.
If it doesn't work:
- The build fails with
CS1929:AddOptimizelyIdentityis chained into.AddCms(). Make it its own statement, as in theStartup.csabove. - The build can't find
AddContentGraphorExperienceData: ausingis missing,Optimizely.Graph.DependencyInjectionorEPiServer.VisualBuilder. - The CMS stops during startup: check that
MappedRolesis gone fromappsettings.Development.json. If the error is about the database, check the connection string and that the database exists. - Sign-in fails with an Opti ID error: the Opti ID Enabled setting may still be provisioning, the keys may come from an environment other than Integration, or the CMS is running on a port other than 5000.
Leave the CMS running for the next step.
Create the application and its start page
The CMS has no pages yet. You'll create the start page together with an application, and the order matters more than it looks.
An application, in CMS 13, ties a start page to the hostnames it's served on. For a headless site, the hostname is the front end's address. This is what gives your pages correct URLs in Graph:
- Without an application, Graph builds URLs from the page's position in the content tree. A page called "homepage" gets the URL
/en/homepage/, and Graph knows no base address for it. The front end would have to request/en/homepage/instead of/. - With an application, the start page's URL is
/, its base address is the front end's (https://localhost:3000), and pages under it get URLs relative to that root.
Graph calculates a page's URL when the page is published. Changing the application or its hostnames later doesn't update content that's already in Graph. So create the application and its hostname first, and publish the start page after that.
Create the application
- In the CMS, open Settings → Applications and click Create Application.
- Application Name:
CMS 13 PaaS Headless Masterclass. The API ID below it fills in automatically (cms13paasheadlessmasterclass). Leave it as it is. - Type: choose Headless.
- Choose Start Page: choose New, then Home Page Experience, the content type you just added. The CMS creates the start page for you, named after the API ID.
- Leave Set as default application and Enable application-specific assets unchecked.
- Click Create Application. The application's Settings page opens and shows the new page under Start Page. That's how you know it worked.
Add the front end's hostname
On the same application, open the Hostnames tab and click Add Hostname:
- Type: Primary
- Hostname:
localhost:3000 - Check Use a secure connection (HTTPS)
- Locale:
en
Save it. The hostname appears in the list. localhost:3000 is where the Next.js front end will run, over HTTPS, as Part 2 explained.
Publish the start page
Go to the CMS editing view and find the new start page in the page tree, named cms13paasheadlessmasterclass. Open it and publish it. It has no content yet, and that's fine: Part 5 fills it.
Until it's published, the page is in Graph as a draft, and the Single Key can't see drafts. Publishing is what makes it visible to the front end.
If you published a page before creating the application or the hostname, publish it again. Otherwise Graph keeps the old /en/... URL.
Optional: check Graph directly
You can ask Graph for the page yourself, without any front-end code. Replace the placeholder with your Single Key:
$singleKey = "<your-single-key>"
$body = @{ query = '{ HomePageExperience { items { _metadata { displayName url { default base } } } } }' } | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri "https://cg.optimizely.com/content/v2?auth=$singleKey" -ContentType 'application/json' -Body $body | ConvertTo-Json -Depth 10You should see your page with "default": "/" and "base": "https://localhost:3000". A (401) Unauthorized error means the key is wrong. An empty items list means the page isn't published yet, or the sync hasn't finished: give it a few seconds and try again.
This check is useful later, too. When the front end shows nothing, it tells you whether the problem is in Graph or in the front end.
Scaffold the front end
Open a second terminal and go back to the repository root, headless-masterclass. The CMS can keep running in the first one.
Create the Next.js app
pnpm create next-app@latest masterclass-webWhen it asks Would you like to use the recommended Next.js defaults?, choose Yes, use recommended defaults. That gives you TypeScript, the App Router, ESLint and Tailwind CSS. The tool notices you're using pnpm and installs everything with it.
Add the Optimizely SDK
Optimizely's cms-create-app tool adds the SDK to an existing Next.js project. Run it inside the new project:
cd masterclass-web
pnpm dlx @optimizely/cms-create-app@latestIt asks three questions:
- What would you like to do? Choose Add Optimizely CMS to this project.
- Add Optimizely CMS SDK? Yes.
- Add Optimizely CMS CLI (for content type syncing)? Yes.
It detects the Next.js project and pnpm on its own, installs @optimizely/cms-sdk and @optimizely/cms-cli, and adds four files:
lib/optimizely.ts: the SDK configuration.app/[...slug]/page.tsx: a page that fetches content from Graph by URL and prints it as JSON. That's exactly the connection check this part needs..env: the environment variables the SDK and CLI read.create-next-appalready keeps.env*files out of Git.optimizely.config.mjs: configuration for pushing content types defined in TypeScript to the CMS. This masterclass defines content types in C#, so you can ignore it.
The tool has two other modes, and I'd skip both. Its templates are complete demo sites that define content types in TypeScript, the opposite of the C# approach from Part 2. Its fresh project mode runs create-next-app for you, but with npm, even if you picked pnpm.
pnpm may print a warning that it ignored a build script for esbuild, a dependency of the CLI. It's safe to leave it that way: the CLI works without it. To silence the warning, run pnpm approve-builds and confirm without selecting anything.
Tidy up what the tool added
Two small fixes. First, the tool added an opti-push script to package.json that calls a command the current CLI doesn't have. Remove it:
pnpm pkg delete scripts.opti-pushSecond, the SDK configuration in lib/optimizely.ts only runs if something imports it. The tool reminds you of this at the end, under Next steps. Open app/layout.tsx and add the import below the existing globals.css import:
import "./globals.css";
import "@/lib/optimizely";Because every page goes through the root layout, the configuration is in place before any page asks Graph for content.
Connect the front end to Graph
Configure the SDK
Replace the contents of lib/optimizely.ts with this:
import { config, contentType, initContentTypeRegistry, initDisplayTemplateRegistry } from '@optimizely/cms-sdk';
import { initReactComponentRegistry } from '@optimizely/cms-sdk/react/server';
config({
apiKey: process.env.OPTIMIZELY_GRAPH_SINGLE_KEY || '',
graphUrl: process.env.OPTIMIZELY_GRAPH_GATEWAY,
platform: 'paas',
});
// The SDK only fetches content whose type is registered here. This is a local
// description used to build Graph queries, not a definition pushed to the CMS:
// the type itself is defined in C# on the CMS side. Replaced in Part 5.
const HomePageExperienceContentType = contentType({
key: 'HomePageExperience',
displayName: 'Home Page Experience',
baseType: '_experience',
});
initContentTypeRegistry([HomePageExperienceContentType]);
initReactComponentRegistry({
resolver: {
// Map content types to React components here, e.g.:
// Article,
},
});
initDisplayTemplateRegistry([]);Two changes from what the tool generated:
platform: 'paas'tells the SDK it's talking to PaaS CMS 13. The default is SaaS CMS.- The
HomePageExperienceregistration. The SDK builds its Graph queries from a registry of content types. If the content at a URL has a type that isn't in the registry, the SDK doesn't throw an error: it quietly returns an empty result. With the tool's empty registry, the page would stay blank even though everything else works. So you describe the one type you have, by the same name as the C# class. This description stays in the front end: nothing is pushed to the CMS. In Part 5,config pullgenerates these descriptions from the CMS and replaces this hand-written one.
Serve the start page at /
The tool's page lives in app/[...slug], a catch-all route that matches any URL with at least one segment, such as /about. It doesn't match / itself, which create-next-app's own app/page.tsx handles. Your start page lives at /, so swap them: rename the folder to the optional catch-all, [[...slug]], which also matches /, and delete app/page.tsx.
Rename-Item -LiteralPath 'app\[...slug]' -NewName '[[...slug]]'
Remove-Item app\page.tsxUse -LiteralPath, not -Path. PowerShell reads square brackets in -Path as a wildcard pattern and reports that the folder doesn't exist.
Then replace the contents of app/[[...slug]]/page.tsx with this:
import { getClient } from '@optimizely/cms-sdk';
type Props = {
params: Promise<{
// Optional catch-all: undefined on the root path (/)
slug?: string[];
}>;
};
export default async function Page({ params }: Props) {
const { slug } = await params;
const client = getClient();
const path = slug ? `/${slug.join('/')}/` : '/';
const content = await client.getContentByPath(path);
return <pre>{JSON.stringify(content[0], null, 2)}</pre>;
}slug holds the URL segments, so /about/team gives ['about', 'team'], and it's undefined on /. The code turns it back into a path and asks Graph for the content at that URL. The trailing slash is there because Graph stores page URLs with one, while Next.js removes it from the address in the browser. The page then prints the result as JSON.
Compared with the generated file, slug is optional and the // @ts-nocheck line at the top is gone. The file type-checks fine without it.
Run the front end over HTTPS
Change the dev script so the development server uses HTTPS, to match the hostname you registered in the CMS:
pnpm pkg set "scripts.dev=next dev --experimental-https"The first time you start it, Next.js creates a local certificate for localhost and asks the operating system to trust it, so Windows may show a security prompt. Accept it. Next.js keeps the certificate in a certificates folder and adds that folder to .gitignore.
Fill in .env
Open .env. It lists eight settings, but this part needs only one. Set it to the Single Key from the PaaS Portal:
OPTIMIZELY_GRAPH_SINGLE_KEY=<your-single-key>Leave everything else as it is. For reference, here's what the rest are for:
| Setting | Used in | Notes |
|---|---|---|
OPTIMIZELY_GRAPH_SINGLE_KEY | This part | The public, read-only Graph key. |
OPTIMIZELY_GRAPH_GATEWAY | Not needed | Commented out. The SDK's default is the same address. |
OPTIMIZELY_CMS_URL | Part 6 | The CMS address, for live preview. Leave it empty for now. |
OPTIMIZELY_CMS_CLIENT_ID, OPTIMIZELY_CMS_CLIENT_SECRET | Part 5 | Credentials for config pull. The hint in the file, "Settings > API Keys", describes SaaS CMS. On PaaS you define them in the CMS, as Part 5 shows. |
OPTIMIZELY_CMS_API_URL | Part 5 | Commented out. On PaaS it's your own CMS (https://localhost:5000 locally), not the SaaS default in the file. |
APPLICATION_HOST | Not needed | Commented out. Limits Graph queries to one site's hostname, which matters with several sites in one CMS. |
NODE_TLS_REJECT_UNAUTHORIZED | Never | Commented out, and keep it that way. It turns off certificate checks for the whole Next.js app. Part 5 trusts the local CMS certificate in a safer way. |
OPTIMIZELY_DXP_PROJECT_ID, ..._CLIENT_KEY, ..._CLIENT_SECRET | Not needed | Commented out. For deploying the front end to Optimizely's own hosting. This masterclass deploys it to Vercel. |
The Single Key is public by design, but keep .env out of Git anyway: later parts add values that aren't.
See it work
Start the development server from masterclass-web:
pnpm devWhen it shows Ready, open https://localhost:3000/. You should see raw JSON like this (shortened):
{
"__typename": "HomePageExperience",
"_metadata": {
"key": "…",
"locale": "en",
"displayName": "cms13paasheadlessmasterclass",
"url": {
"type": "HIERARCHICAL",
"default": "/",
"base": "https://localhost:3000"
},
"status": "Published"
},
"composition": {
"__typename": "CompositionStructureNode"
}
}That's your CMS start page, fetched from Graph. Check three things:
"__typename": "HomePageExperience": the SDK found the page and knows its type."default": "/"and"base": "https://localhost:3000": the application and hostname work.composition: the page's Visual Builder layout, empty for now. Part 5 fills and renders it.
Here's a detail worth noticing: stop the CMS and reload the page. It still works. The front end reads from Graph, not from the CMS, which is the architecture from Part 2 in action.
Next.js may also show an issue indicator in the corner of the page, flagging the route as blocking. That comes from Cache Components, a caching model that new Next.js projects now switch on by default (cacheComponents: true in next.config.ts). It doesn't stop anything from working in development, but it does mean pnpm build doesn't pass with this page yet. Leave it for now: we'll deal with it in a later part, once the page renders real content and needs a production build.
Troubleshooting
The page shows an empty box. The SDK found nothing to return. It doesn't report this as an error, so check, in this order: is HomePageExperience registered in lib/optimizely.ts, with exactly that name? Is the start page published? Run the optional Graph check above: if Graph returns the page, the problem is in the front end. If Graph returns it with an /en/... URL, publish the page again.
An error says Invalid Optimizely Graph API key: key must be a non-empty string. OPTIMIZELY_GRAPH_SINGLE_KEY is empty or missing in .env.
An error says HTTP 401: Unauthorized. The Single Key is wrong. Copy it again from the PaaS Portal. Make sure it's the Single Key, not the App Key.
/ returns a 404 after you renamed the route folder. The development server was running during the rename. Stop it with Ctrl+C and run pnpm dev again.
Your normal browser shows HTTP 431 Request Header Fields Too Large, but a private window works. Browsers send cookies by host name, not by port. So the cookies the CMS sets on localhost:5000 when you sign in also go to localhost:3000. If they add up to more than 16 KB, Node.js rejects the request. It didn't happen in my tests on CMS 13.6.0, but it did on an earlier version, and cookies from other local apps add up too. The fix is a file called .npmrc in masterclass-web, next to package.json, with one line:
node-options=--max-http-header-size=65536pnpm passes this option to Node.js for every script, so pnpm dev accepts up to 64 KB of headers. Restart pnpm dev after adding it. Clearing your cookies would also work, but it signs you out of the CMS, and the cookies come back the next time you sign in.
Trade-offs and limitations
- The content type registration is temporary. Describing types by hand doesn't scale and drifts from the C# code. Part 5 replaces it with types generated by
config pull. - Cache Components is on, but not dealt with yet. The page works in development, and
pnpm buildfails on it until a later part sorts it out. - The setup is local only. The Opti ID dev key works against the Integration environment from your machine, and User Secrets only exist on your machine. Deployed environments get their configuration another way, which Part 4 covers.
- The SDK and its tools move fast.
cms-create-app1.1.0 still needs the fixes from this part. A newer version may need fewer, or different ones.
What's next
In Part 4, Deployment: Vercel and DXP, you'll deploy both projects: the front end to Vercel and the CMS to DXP, so the setup from this part runs somewhere other than your machine.