Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import DOMPurify from "isomorphic-dompurify";
import { getPage, stack } from "@/lib/contentstack";
import { getPage, getStack } from "@/lib/contentstack";
import { headers } from "next/headers";
import Image from "next/image";

Expand All @@ -17,6 +17,8 @@ export default async function Home({
const { live_preview, entry_uid, content_type_uid, preview_timestamp } =
await searchParams;

const stack = getStack();

if (live_preview) {
stack.livePreviewQuery({
live_preview,
Expand All @@ -26,7 +28,7 @@ export default async function Home({
});
}

const page = await getPage("/");
const page = await getPage("/", stack);

return (
<main className="max-w-(--breakpoint-md) mx-auto">
Expand Down
96 changes: 76 additions & 20 deletions lib/contentstack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,62 @@ import ContentstackLivePreview, { IStackSdk } from "@contentstack/live-preview-u
import { getContentstackEndpoints, getRegionForString } from "@timbenniks/contentstack-endpoints";
import { Page } from "./types";

// Region and endpoint configuration - computed once at module load time
const region = getRegionForString(process.env.NEXT_PUBLIC_CONTENTSTACK_REGION as string)
const endpoints = getContentstackEndpoints(region, true)

export const stack = contentstack.stack({
apiKey: process.env.NEXT_PUBLIC_CONTENTSTACK_API_KEY as string,
deliveryToken: process.env.NEXT_PUBLIC_CONTENTSTACK_DELIVERY_TOKEN as string,
environment: process.env.NEXT_PUBLIC_CONTENTSTACK_ENVIRONMENT as string,
// Setting the region
// if the region doesnt exist, fall back to a custom region given by the env vars
// for internal testing purposes at Contentstack we look for a custom region in the env vars, you do not have to do this.
region: region ? region : process.env.NEXT_PUBLIC_CONTENTSTACK_REGION as any,
// Setting the host for content delivery based on the region or environment variables
// This is done for internal testing purposes at Contentstack, you can omit this if you have set a region above.
host: process.env.NEXT_PUBLIC_CONTENTSTACK_CONTENT_DELIVERY || endpoints && endpoints.contentDelivery,
/**
* Creates a new Contentstack SDK instance for each request.
*
* IMPORTANT: This function MUST be called for each server-side request to ensure isolation.
*
* Why isolated instances are critical:
* - When Live Preview is enabled, the SDK modifies its configuration (API endpoints, etc.)
* for specific requests via livePreviewQuery()
* - Sharing a single SDK instance across concurrent requests causes configuration changes
* from one user (User A) to affect others (User B), leading to incorrect content delivery
* - Each request gets its own isolated stack instance, preventing cross-request interference
*
* Usage:
* - Server-side: Always call getStack() at the start of each request handler
* - Client-side: Can reuse instances as there's no concurrent request handling
*/
export function getStack() {
// Create a fresh stack instance with base configuration
return contentstack.stack({
apiKey: process.env.NEXT_PUBLIC_CONTENTSTACK_API_KEY as string,
deliveryToken: process.env.NEXT_PUBLIC_CONTENTSTACK_DELIVERY_TOKEN as string,
environment: process.env.NEXT_PUBLIC_CONTENTSTACK_ENVIRONMENT as string,
// Setting the region
// if the region doesnt exist, fall back to a custom region given by the env vars
// for internal testing purposes at Contentstack we look for a custom region in the env vars, you do not have to do this.
region: region ? region : process.env.NEXT_PUBLIC_CONTENTSTACK_REGION as any,
// Setting the host for content delivery based on the region or environment variables
// This is done for internal testing purposes at Contentstack, you can omit this if you have set a region above.
host: process.env.NEXT_PUBLIC_CONTENTSTACK_CONTENT_DELIVERY || endpoints && endpoints.contentDelivery,

live_preview: {
enable: process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW === 'true',
preview_token: process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW_TOKEN,
// Setting the host for live preview based on the region
// for internal testing purposes at Contentstack we look for a custom host in the env vars, you do not have to do this.
host: process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW_HOST || endpoints && endpoints.preview
}
});
live_preview: {
enable: process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW === 'true',
preview_token: process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW_TOKEN,
// Setting the host for live preview based on the region
// for internal testing purposes at Contentstack we look for a custom host in the env vars, you do not have to do this.
host: process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW_HOST || endpoints && endpoints.preview
}
});
}

/**
* Initializes Contentstack Live Preview for client-side editing.
*
* This function is called once on the client-side (via ContentstackLivePreview component)
* to enable the visual editing interface. It creates a stack instance to read configuration
* but doesn't perform any server-side queries, so it's safe to call getStack() here.
*
* Note: This is client-side only and doesn't affect server-side request isolation.
*/
export function initLivePreview() {
// Create a stack instance to read configuration for Live Preview initialization
const stack = getStack();
ContentstackLivePreview.init({
ssr: true,
enable: process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW === 'true',
Expand All @@ -50,7 +81,30 @@ export function initLivePreview() {
});
}

export async function getPage(url: string) {
/**
* Fetches a page entry from Contentstack by URL.
*
* This function is focused solely on fetching page data - it does not handle Live Preview
* configuration. Live Preview setup should be done by the caller before passing the stack instance.
*
* @param url - The URL path to match against the page entry's url field
* @param stackInstance - Optional pre-configured stack instance. If provided, uses this instance
* (useful when Live Preview has been configured). If not provided, creates
* a new isolated stack instance via getStack().
*
* Usage pattern for Live Preview:
* 1. Create a stack: const stack = getStack()
* 2. Configure Live Preview: stack.livePreviewQuery({ ... })
* 3. Pass to getPage: const page = await getPage("/", stack)
*
* Usage pattern without Live Preview:
* const page = await getPage("/") // Creates its own isolated stack
*/
export async function getPage(url: string, stackInstance?: ReturnType<typeof getStack>) {
// Use provided stack instance (with Live Preview config) or create a new isolated one
const stack = stackInstance || getStack();

// Query Contentstack for the page entry matching the URL
const result = await stack
.contentType("page")
.entry()
Expand All @@ -61,6 +115,8 @@ export async function getPage(url: string) {
if (result.entries) {
const entry = result.entries[0]

// Add editable tags for Live Preview if enabled
// These tags enable the visual editing interface to identify editable fields
if (process.env.NEXT_PUBLIC_CONTENTSTACK_PREVIEW === 'true') {
contentstack.Utils.addEditableTags(entry, 'page', true);
}
Expand Down
Loading