Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: Remove CMS code from the `www` app (#42648)

Ivan Vasilov21d7ac051867
diff --git a/apps/www/.env.local.example b/apps/www/.env.local.example
index d6fee8a9b0a..7aeebf4c668 100644
--- a/apps/www/.env.local.example
+++ b/apps/www/.env.local.example
@@ -13,5 +13,3 @@ SUPABASE_COM_SERVICE_ROLE_KEY="secret"
NEXT_PUBLIC_URL="http://localhost:3000"
NEXT_PUBLIC_HCAPTCHA_SITE_KEY="10000000-ffff-ffff-ffff-000000000001"
HCAPTCHA_SECRET_KEY="0x0000000000000000000000000000000000000000"
-CMS_API_KEY=secret
-CMS_PREVIEW_SECRET=secret
diff --git a/apps/www/.vercelignore b/apps/www/.vercelignore
index a0cfdb5c687..30470ae55a6 100644
--- a/apps/www/.vercelignore
+++ b/apps/www/.vercelignore
@@ -60,7 +60,6 @@ Thumbs.db
**/node_modules/framer-motion
# Other apps (since we're only deploying www)
-../cms
../design-system
../docs
../studio
diff --git a/apps/www/README.md b/apps/www/README.md
index 44122a4176b..de8fd244143 100644
--- a/apps/www/README.md
+++ b/apps/www/README.md
@@ -65,10 +65,6 @@ For social sharing (Open Graph meta tags):
- Priority 2: `imgThumb` (if `imgSocial` is missing)
- Priority 3: No fallback (undefined)
-Special case for CMS posts:
-
-- CMS posts may also have a `meta.image` field which takes highest priority for social sharing when available.
-
What happens if fields are not provided?
- If only `imgThumb` is provided: Site displays the image correctly, social sharing uses `imgThumb` as fallback
diff --git a/apps/www/app/api-v2/blog-posts/route.ts b/apps/www/app/api-v2/blog-posts/route.ts
index 2ac79b060e1..72576b9df55 100644
--- a/apps/www/app/api-v2/blog-posts/route.ts
+++ b/apps/www/app/api-v2/blog-posts/route.ts
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
-import { getSortedPosts } from 'lib/posts'
-import { getAllCMSPosts } from 'lib/get-cms-posts'
+
+import { getSortedPosts } from '@/lib/posts'
export const revalidate = 30
@@ -20,11 +20,8 @@ async function getCombinedPosts() {
// Get static blog posts
const staticPosts = getSortedPosts({ directory: '_blog' })
- // Get CMS posts
- const cmsPosts = await getAllCMSPosts({ limit: 100 })
-
// Combine and sort by date
- const allPosts = [...staticPosts, ...cmsPosts].sort((a: any, b: any) => {
+ const allPosts = [...staticPosts].sort((a: any, b: any) => {
const dateA = new Date(a.date || a.formattedDate).getTime()
const dateB = new Date(b.date || b.formattedDate).getTime()
return dateB - dateA
diff --git a/apps/www/app/api-v2/cms-posts/route.ts b/apps/www/app/api-v2/cms-posts/route.ts
deleted file mode 100644
index d8cdc7382f8..00000000000
--- a/apps/www/app/api-v2/cms-posts/route.ts
+++ /dev/null
@@ -1,777 +0,0 @@
-import { draftMode } from 'next/headers'
-import { NextRequest, NextResponse } from 'next/server'
-import { CMS_SITE_ORIGIN } from '~/lib/constants'
-import { generateReadingTime } from '~/lib/helpers'
-
-// Lightweight runtime for better performance
-export const runtime = 'edge'
-
-const corsHeaders = {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
-}
-
-const cfHeaders = {
- 'CF-Access-Client-Id': process.env.CF_ACCESS_CLIENT_ID ?? '',
- 'CF-Access-Client-Secret': process.env.CF_ACCESS_CLIENT_SECRET ?? '',
-}
-
-// Lightweight TOC generation for edge runtime
-type TocItem = { content: string; slug: string; lvl: number }
-
-function generateTocFromMarkdown(markdown: string, maxDepth: number = 2) {
- const lines = markdown.split(/\r?\n/)
- const items: TocItem[] = []
-
- for (const line of lines) {
- const match = /^(#{1,6})\s+(.*)$/.exec(line)
- if (!match) continue
- const depth = match[1].length
- if (depth > maxDepth) continue
- const text = match[2].trim()
- if (!text) continue
-
- const slug = text
- .trim()
- .toLowerCase()
- .replace(/[`~!@#$%^&*()+=|{}\[\]\\:\";'<>?,./]+/g, '')
- .replace(/\s+/g, '-')
-
- items.push({ content: text, slug, lvl: depth })
- }
-
- const content = items
- .map((h) => `${' '.repeat(Math.max(0, h.lvl - 1))}- [${h.content}](#${h.slug})`)
- .join('\n')
-
- return { content, json: items }
-}
-
-// Minimal rich-text to plain text for reading time
-function richTextToPlainText(content: any): string {
- try {
- const blocks = content?.root?.children
- if (!Array.isArray(blocks)) return ''
- const segments: string[] = []
- for (const node of blocks) {
- if (node?.type === 'heading') {
- const text = Array.isArray(node.children)
- ? node.children.map((c: any) => c?.text || '').join('')
- : ''
- if (text) segments.push(text)
- } else if (node?.type === 'paragraph') {
- const text = Array.isArray(node.children)
- ? node.children.map((c: any) => c?.text || '').join('')
- : ''
- if (text) segments.push(text)
- } else if (node?.type === 'list') {
- const items = Array.isArray(node.children)
- ? node.children
- .map((item: any) =>
- Array.isArray(item?.children)
- ? item.children.map((c: any) => c?.text || '').join('')
- : ''
- )
- .filter(Boolean)
- : []
- if (items.length > 0) segments.push(items.join(' '))
- } else if (node?.type === 'link') {
- const text = Array.isArray(node.children)
- ? node.children.map((c: any) => c?.text || '').join('')
- : ''
- if (text) segments.push(text)
- }
- }
- return segments.join('\n')
- } catch {
- return ''
- }
-}
-
-// Convert Payload rich text content to markdown
-function convertRichTextToMarkdown(content: any): string {
- if (!content?.root?.children) return ''
-
- return content.root.children
- .map((node: any) => {
- if (node.type === 'heading') {
- const level = node.tag && typeof node.tag === 'string' ? node.tag.replace('h', '') : '1'
- const text = node.children?.map((child: any) => child.text).join('') || ''
- return `${'#'.repeat(Number(level))} ${text}`
- }
- if (node.type === 'paragraph') {
- return node.children?.map((child: any) => child.text).join('') || ''
- }
- if (node.type === 'list') {
- const items = node.children
- ?.map((item: any) => {
- if (item.type === 'list-item') {
- return `- ${item.children?.map((child: any) => child.text).join('') || ''}`
- }
- return ''
- })
- .filter(Boolean)
- .join('\n')
- return items
- }
- if (node.type === 'link') {
- const text = node.children?.map((child: any) => child.text).join('') || ''
- const url = node.url || ''
- return `[${text}](${url})`
- }
- return ''
- })
- .filter(Boolean)
- .join('\n\n')
-}
-
-// Handle preflight requests
-export async function OPTIONS() {
- return new Response(null, {
- status: 200,
- headers: corsHeaders,
- })
-}
-
-export async function GET(request: NextRequest) {
- try {
- const { searchParams } = new URL(request.url)
- const mode = searchParams.get('mode') || 'preview' // 'preview' or 'full'
- const limit = searchParams.get('limit') || '100'
- const slug = searchParams.get('slug') // For fetching specific post
- const draftParam = searchParams.get('draft') === 'true' // Explicit draft parameter
-
- const baseUrl = CMS_SITE_ORIGIN
- const apiKey = process.env.CMS_API_KEY
-
- // Check if we're in draft mode (either Next.js draft mode OR explicit draft parameter)
- const { isEnabled: isDraftMode } = await draftMode()
- const shouldFetchDraft = isDraftMode || draftParam
-
- // When fetching a specific post, we need to handle versioning correctly
- if (slug) {
- // If in draft mode, fetch the latest version (draft or published)
- if (shouldFetchDraft) {
- // Strategy 1: Try to get the latest version from versions API (including drafts)
- const allVersionsUrl = new URL('/api/posts/versions', baseUrl)
- allVersionsUrl.searchParams.set('where[version.slug][equals]', slug)
- allVersionsUrl.searchParams.set('sort', '-updatedAt') // Get the most recent version regardless of status
- allVersionsUrl.searchParams.set('limit', '1')
- allVersionsUrl.searchParams.set('depth', '2')
-
- const allVersionsResponse = await fetch(allVersionsUrl.toString(), {
- headers: {
- 'Content-Type': 'application/json',
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- ...cfHeaders,
- },
- cache: 'no-store',
- })
-
- if (allVersionsResponse.ok) {
- const versionsData = await allVersionsResponse.json()
-
- if (versionsData.docs && versionsData.docs.length > 0) {
- const latestVersion = versionsData.docs[0].version
- if (latestVersion) {
- const markdownContent = convertRichTextToMarkdown(latestVersion.content)
- const readingTime = generateReadingTime(richTextToPlainText(latestVersion.content))
-
- const tocResult = generateTocFromMarkdown(
- markdownContent,
- latestVersion.toc_depth || 3
- )
-
- const processedPost = {
- slug: latestVersion.slug || '',
- title: latestVersion.title || '',
- description: latestVersion.description || '',
- date: latestVersion.date || new Date().toISOString(),
- formattedDate: new Date(latestVersion.date || new Date()).toLocaleDateString(
- 'en-US',
- {
- month: 'long',
- day: 'numeric',
- year: 'numeric',
- }
- ),
- readingTime,
- authors: Array.isArray(latestVersion.authors)
- ? latestVersion.authors.map((a: any) => ({
- author: a?.author || 'Unknown Author',
- author_id: a?.author_id || '',
- position: a?.position || '',
- author_url: a?.author_url || '#',
- author_image_url: a?.author_image_url?.url
- ? typeof a.author_image_url.url === 'string' &&
- a.author_image_url.url.includes('http')
- ? a.author_image_url.url
- : `${baseUrl}${a.author_image_url.url}`
- : null,
- username: a?.username || '',
- }))
- : [],
- imgThumb: latestVersion.imgThumb?.url
- ? `${baseUrl}${latestVersion.imgThumb.url}`
- : undefined,
- imgSocial: latestVersion.imgSocial?.url
- ? `${baseUrl}${latestVersion.imgSocial.url}`
- : undefined,
- meta: latestVersion.meta || null,
- url: `/blog/${latestVersion.slug}`,
- path: `/blog/${latestVersion.slug}`,
- tags: latestVersion.tags || [],
- categories: [],
- isCMS: true,
- content: markdownContent,
- richContent: latestVersion.content,
- toc: tocResult,
- toc_depth: latestVersion.toc_depth || 3,
- isDraft: true,
- _status: latestVersion._status,
- }
-
- return NextResponse.json(
- {
- success: true,
- post: processedPost,
- mode,
- isDraft: shouldFetchDraft,
- },
- { headers: corsHeaders }
- )
- }
- }
- }
-
- // Strategy 2: Try to get the most recent draft
- const draftUrl = new URL('/api/posts', baseUrl)
- draftUrl.searchParams.set('where[slug][equals]', slug)
- draftUrl.searchParams.set('depth', '2')
- draftUrl.searchParams.set('draft', 'true')
- draftUrl.searchParams.set('sort', '-updatedAt') // Get the most recent version
-
- const draftResponse = await fetch(draftUrl.toString(), {
- headers: {
- 'Content-Type': 'application/json',
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- ...cfHeaders,
- },
- cache: 'no-store', // Never cache draft content
- })
-
- if (draftResponse.ok) {
- const draftData = await draftResponse.json()
-
- if (draftData.docs && draftData.docs.length > 0) {
- const post = draftData.docs[0]
- const markdownContent = convertRichTextToMarkdown(post.content)
- const readingTime = generateReadingTime(richTextToPlainText(post.content))
-
- const tocResult = generateTocFromMarkdown(markdownContent, post.toc_depth || 3)
-
- const processedPost = {
- slug: post.slug || '',
- title: post.title || '',
- description: post.description || '',
- date: post.date || new Date().toISOString(),
- formattedDate: new Date(post.date || new Date()).toLocaleDateString('en-US', {
- month: 'long',
- day: 'numeric',
- year: 'numeric',
- }),
- readingTime,
- authors: Array.isArray(post.authors)
- ? post.authors.map((a: any) => ({
- author: a?.author || 'Unknown Author',
- author_id: a?.author_id || '',
- position: a?.position || '',
- author_url: a?.author_url || '#',
- author_image_url: a?.author_image_url?.url
- ? typeof a.author_image_url.url === 'string' &&
- a.author_image_url.url.includes('http')
- ? a.author_image_url.url
- : `${baseUrl}${a.author_image_url.url}`
- : null,
- username: a?.username || '',
- }))
- : [],
- imgThumb: post.imgThumb?.url ? `${baseUrl}${post.imgThumb.url}` : undefined,
- imgSocial: post.imgSocial?.url ? `${baseUrl}${post.imgSocial.url}` : undefined,
- meta: post.meta || null,
- url: `/blog/${post.slug}`,
- path: `/blog/${post.slug}`,
- tags: post.tags || [],
- categories: [],
- isCMS: true,
- content: markdownContent,
- richContent: post.content,
- toc: tocResult,
- toc_depth: post.toc_depth || 3,
- isDraft: true,
- _status: post._status,
- }
-
- return NextResponse.json(
- {
- success: true,
- post: processedPost,
- mode,
- isDraft: shouldFetchDraft,
- },
- { headers: corsHeaders }
- )
- }
- }
-
- // Strategy 3: If no draft found, try published version but still mark as draft mode
-
- const publishedUrl = new URL('/api/posts', baseUrl)
- publishedUrl.searchParams.set('where[slug][equals]', slug)
- publishedUrl.searchParams.set('depth', '2')
- publishedUrl.searchParams.set('draft', 'false')
-
- const publishedResponse = await fetch(publishedUrl.toString(), {
- headers: {
- 'Content-Type': 'application/json',
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- ...cfHeaders,
- },
- cache: 'no-store',
- })
-
- if (publishedResponse.ok) {
- const publishedData = await publishedResponse.json()
- if (publishedData.docs && publishedData.docs.length > 0) {
- const post = publishedData.docs[0]
- const markdownContent = convertRichTextToMarkdown(post.content)
- const readingTime = generateReadingTime(richTextToPlainText(post.content))
-
- const tocResult = generateTocFromMarkdown(markdownContent, post.toc_depth || 3)
-
- const processedPost = {
- slug: post.slug || '',
- title: post.title || '',
- description: post.description || '',
- date: post.date || new Date().toISOString(),
- formattedDate: new Date(post.date || new Date()).toLocaleDateString('en-US', {
- month: 'long',
- day: 'numeric',
- year: 'numeric',
- }),
- readingTime,
- authors: Array.isArray(post.authors)
- ? post.authors.map((a: any) => ({
- author: a?.author || 'Unknown Author',
- author_id: a?.author_id || '',
- position: a?.position || '',
- author_url: a?.author_url || '#',
- author_image_url: a?.author_image_url?.url
- ? typeof a.author_image_url.url === 'string' &&
- a.author_image_url.url.includes('http')
- ? a.author_image_url.url
- : `${baseUrl}${a.author_image_url.url}`
- : null,
- username: a?.username || '',
- }))
- : [],
- imgThumb: post.imgThumb?.url ? `${baseUrl}${post.imgThumb.url}` : undefined,
- imgSocial: post.imgSocial?.url ? `${baseUrl}${post.imgSocial.url}` : undefined,
- meta: post.meta || null,
- url: `/blog/${post.slug}`,
- path: `/blog/${post.slug}`,
- tags: post.tags || [],
- categories: [],
- isCMS: true,
- content: markdownContent,
- richContent: post.content,
- toc: tocResult,
- toc_depth: post.toc_depth || 3,
- isDraft: true,
- _status: post._status,
- }
-
- return NextResponse.json(
- {
- success: true,
- post: processedPost,
- mode,
- isDraft: shouldFetchDraft,
- },
- { headers: corsHeaders }
- )
- }
- }
- }
-
- // Strategy 1: Try to get the latest published version using the versions API
- const versionsUrl = new URL('/api/posts/versions', baseUrl)
- versionsUrl.searchParams.set('where[version.slug][equals]', slug)
- versionsUrl.searchParams.set('where[version._status][equals]', 'published')
- versionsUrl.searchParams.set('sort', '-createdAt') // Use createdAt instead of updatedAt for versions
- versionsUrl.searchParams.set('limit', '1')
- versionsUrl.searchParams.set('depth', '2')
-
- const versionsResponse = await fetch(versionsUrl.toString(), {
- headers: {
- 'Content-Type': 'application/json',
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- ...cfHeaders,
- },
- // For published posts: allow caching with revalidation
- next: { revalidate: 60 }, // 1 minute
- })
-
- if (versionsResponse.ok) {
- const versionsData = await versionsResponse.json()
-
- if (versionsData.docs && versionsData.docs.length > 0) {
- const latestPublishedVersion = versionsData.docs[0].version
-
- if (latestPublishedVersion) {
- const post = latestPublishedVersion
- const markdownContent = convertRichTextToMarkdown(post.content)
- const plain = richTextToPlainText(post.content)
- const readingTime = generateReadingTime(plain)
- const tocResult = generateTocFromMarkdown(markdownContent, post.toc_depth || 3)
-
- const processedPost = {
- type: 'blog' as const,
- slug: post.slug,
- title: post.title || '',
- description: post.description || '',
- date: post.date || post.createdAt || new Date().toISOString(),
- formattedDate: new Date(post.date || post.createdAt || new Date()).toLocaleDateString(
- 'en-IN',
- { month: 'long', day: 'numeric', year: 'numeric' }
- ),
- readingTime,
- authors: Array.isArray(post.authors)
- ? post.authors.map((a: any) => ({
- author: a?.author || 'Unknown Author',
- author_id: a?.author_id || '',
- position: a?.position || '',
- author_url: a?.author_url || '#',
- author_image_url: a?.author_image_url?.url
- ? typeof a.author_image_url.url === 'string' &&
- a.author_image_url.url.includes('http')
- ? a.author_image_url.url
- : `${baseUrl}${a.author_image_url.url}`
- : null,
- username: a?.username || '',
- }))
- : [],
- imgThumb: post.imgThumb?.url
- ? typeof post.imgThumb.url === 'string' && post.imgThumb.url.includes('http')
- ? post.imgThumb.url
- : `${baseUrl}${post.imgThumb.url}`
- : '',
- imgSocial: post.imgSocial?.url
- ? typeof post.imgSocial.url === 'string' && post.imgSocial.url.includes('http')
- ? post.imgSocial.url
- : `${baseUrl}${post.imgSocial.url}`
- : undefined,
- meta: post.meta || null,
- url: `/blog/${post.slug}`,
- path: `/blog/${post.slug}`,
- tags: post.tags || [],
- categories: [],
- isCMS: true,
- content: mode === 'full' ? markdownContent : undefined,
- richContent: mode === 'full' ? post.content : undefined,
- toc: tocResult,
- toc_depth: post.toc_depth || 3,
- }
-
- return NextResponse.json(
- {
- success: true,
- post: processedPost,
- mode,
- source: 'versions-api',
- },
- { headers: corsHeaders }
- )
- }
- }
- } else {
- if (process.env.NODE_ENV !== 'production') {
- console.log('[cms-posts] Versions API failed, response:', await versionsResponse.text())
- }
- }
-
- // Strategy 2: If versions API didn't work, try finding the parent post first, then get its latest published version
-
- const parentUrl = new URL('/api/posts', baseUrl)
- parentUrl.searchParams.set('where[slug][equals]', slug)
- parentUrl.searchParams.set('limit', '1')
- parentUrl.searchParams.set('depth', '0') // Just get the ID
-
- const parentResponse = await fetch(parentUrl.toString(), {
- headers: {
- 'Content-Type': 'application/json',
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- ...cfHeaders,
- },
- next: { revalidate: 60 }, // 1 minute for published posts
- })
-
- if (parentResponse.ok) {
- const parentData = await parentResponse.json()
- if (parentData.docs && parentData.docs.length > 0) {
- const parentId = parentData.docs[0].id
-
- // Now get the latest published version of this specific post
- const versionsByParentUrl = new URL('/api/posts/versions', baseUrl)
- versionsByParentUrl.searchParams.set('where[parent][equals]', parentId)
- versionsByParentUrl.searchParams.set('where[version._status][equals]', 'published')
- versionsByParentUrl.searchParams.set('sort', '-createdAt')
- versionsByParentUrl.searchParams.set('limit', '1')
- versionsByParentUrl.searchParams.set('depth', '2')
-
- const versionsByParentResponse = await fetch(versionsByParentUrl.toString(), {
- headers: {
- 'Content-Type': 'application/json',
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- ...cfHeaders,
- },
- next: { revalidate: 60 }, // 1 minute for published posts
- })
-
- if (versionsByParentResponse.ok) {
- const versionsByParentData = await versionsByParentResponse.json()
-
- if (versionsByParentData.docs && versionsByParentData.docs.length > 0) {
- const latestPublishedVersion = versionsByParentData.docs[0].version
-
- if (latestPublishedVersion) {
- const post = latestPublishedVersion
- const markdownContent = convertRichTextToMarkdown(post.content)
- const plain = richTextToPlainText(post.content)
- const readingTime = generateReadingTime(plain)
-
- const processedPost = {
- type: 'blog' as const,
- slug: post.slug,
- title: post.title || '',
- description: post.description || '',
- date: post.date || post.createdAt || new Date().toISOString(),
- formattedDate: new Date(
- post.date || post.createdAt || new Date()
- ).toLocaleDateString('en-IN', { month: 'long', day: 'numeric', year: 'numeric' }),
- readingTime,
- authors: Array.isArray(post.authors)
- ? post.authors.map((a: any) => ({
- author: a?.author || 'Unknown Author',
- author_id: a?.author_id || '',
- position: a?.position || '',
- author_url: a?.author_url || '#',
- author_image_url: a?.author_image_url?.url
- ? typeof a.author_image_url.url === 'string' &&
- a.author_image_url.url.includes('http')
- ? a.author_image_url.url
- : `${baseUrl}${a.author_image_url.url}`
- : null,
- username: a?.username || '',
- }))
- : [],
- imgThumb: post.imgThumb?.url
- ? typeof post.imgThumb.url === 'string' && post.imgThumb.url.includes('http')
- ? post.imgThumb.url
- : `${baseUrl}${post.imgThumb.url}`
- : '',
- imgSocial: post.imgSocial?.url
- ? typeof post.imgSocial.url === 'string' && post.imgSocial.url.includes('http')
- ? post.imgSocial.url
- : `${baseUrl}${post.imgSocial.url}`
- : undefined,
- url: `/blog/${post.slug}`,
- path: `/blog/${post.slug}`,
- tags: post.tags || [],
- categories: [],
- isCMS: true,
- content: mode === 'full' ? markdownContent : undefined,
- richContent: mode === 'full' ? post.content : undefined,
- }
-
- return NextResponse.json(
- {
- success: true,
- post: processedPost,
- mode,
- source: 'versions-by-parent-api',
- },
- { headers: corsHeaders }
- )
- }
- }
- }
- }
- }
- }
-
- // Fallback to regular posts API for listing or if versions API fails
- const url = new URL('/api/posts', baseUrl)
- url.searchParams.set('depth', '2')
- url.searchParams.set('draft', 'false')
- url.searchParams.set('limit', limit)
- url.searchParams.set('where[_status][equals]', 'published')
-
- // If fetching specific post by slug (fallback)
- if (slug) {
- url.searchParams.set('where[slug][equals]', slug)
- url.searchParams.set('limit', '1')
- }
-
- const response = await fetch(url.toString(), {
- headers: {
- 'Content-Type': 'application/json',
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- ...cfHeaders,
- },
- // For individual post requests, don't cache to ensure fresh data
- cache: slug ? 'no-store' : 'default',
- next: slug ? undefined : { revalidate: 300 },
- // Add SSL configuration for production
- ...(process.env.NODE_ENV === 'production' && {
- // Allow self-signed certificates in development, but use proper SSL in production
- // This helps with Vercel's internal networking
- agent: false,
- }),
- })
-
- if (!response.ok) {
- console.error('[cms-posts] Non-OK response:', response.status, response.statusText)
- return NextResponse.json(
- {
- success: false,
- error: 'Failed to fetch posts from CMS',
- status: response.status,
- },
- { status: response.status, headers: corsHeaders }
- )
- }
-
- const contentType = response.headers.get('content-type') || ''
- if (!contentType.toLowerCase().includes('application/json')) {
- console.error('[cms-posts] Non-JSON response, content-type:', contentType)
- return NextResponse.json(
- {
- success: false,
- error: 'CMS returned non-JSON response',
- contentType,
- },
- { status: 502, headers: corsHeaders }
- )
- }
-
- const data = await response.json()
- const docs = Array.isArray(data?.docs) ? data.docs : []
-
- const dateFmt: Intl.DateTimeFormatOptions = { month: 'long', day: 'numeric', year: 'numeric' }
- const posts = docs
- .filter((p: any) => !!p?.slug)
- .map((p: any) => {
- const imgThumbUrl = p?.imgThumb?.url
- ? typeof p.imgThumb.url === 'string' && p.imgThumb.url.includes('http')
- ? p.imgThumb.url
- : `${baseUrl}${p.imgThumb.url}`
- : ''
- const imgSocialUrl = p?.imgSocial?.url
- ? typeof p.imgSocial.url === 'string' && p.imgSocial.url.includes('http')
- ? p.imgSocial.url
- : `${baseUrl}${p.imgSocial.url}`
- : ''
- const date = p.date || p.createdAt || new Date().toISOString()
- const formattedDate = new Date(date).toLocaleDateString('en-IN', dateFmt)
- const plain = richTextToPlainText(p?.content)
- const readingTime = generateReadingTime(plain)
-
- const authors = Array.isArray(p?.authors)
- ? p.authors.map((a: any) => ({
- author: a?.author || 'Unknown Author',
- author_id: a?.author_id || '',
- position: a?.position || '',
- author_url: a?.author_url || '#',
- author_image_url: a?.author_image_url?.url
- ? typeof a.author_image_url.url === 'string' &&
- a.author_image_url.url.includes('http')
- ? a.author_image_url.url
- : `${baseUrl}${a.author_image_url.url}`
- : null,
- username: a?.username || '',
- }))
- : []
-
- // Base post structure (always included)
- const basePost = {
- type: 'blog' as const,
- slug: p.slug,
- title: p.title || '',
- description: p.description || '',
- date,
- formattedDate,
- readingTime,
- authors,
- imgThumb: imgThumbUrl || imgSocialUrl || '',
- imgSocial: imgSocialUrl || undefined,
- meta: p.meta || null,
- url: `/blog/${p.slug}`,
- path: `/blog/${p.slug}`,
- tags: p.tags || [],
- categories: [],
- isCMS: true,
- toc_depth: p.toc_depth || 3,
- }
-
- // Add content for full mode
- if (mode === 'full') {
- const markdownContent = convertRichTextToMarkdown(p.content)
- const tocResult = generateTocFromMarkdown(markdownContent, p.toc_depth || 3)
- return {
- ...basePost,
- content: markdownContent, // Convert rich text to markdown for MDX processing
- richContent: p.content, // Keep original rich text for reference
- toc: tocResult,
- toc_depth: p.toc_depth || 3,
- }
- }
-
- return basePost
- })
- .sort((a: any, b: any) => new Date(b.date).getTime() - new Date(a.date).getTime())
-
- // For single post requests, return the post directly
- if (slug && posts.length > 0) {
- return NextResponse.json(
- {
- success: true,
- post: posts[0],
- mode,
- },
- { headers: corsHeaders }
- )
- }
-
- return NextResponse.json(
- {
- success: true,
- posts,
- total: posts.length,
- mode,
- cached: true,
- },
- { headers: corsHeaders }
- )
- } catch (error) {
- console.error('[cms-posts] Error:', error)
- return NextResponse.json(
- {
- success: false,
- error: 'Internal server error',
- message: error instanceof Error ? error.message : 'Unknown error',
- },
- { status: 500, headers: corsHeaders }
- )
- }
-}
diff --git a/apps/www/app/api-v2/cms/disable-draft/route.ts b/apps/www/app/api-v2/cms/disable-draft/route.ts
deleted file mode 100644
index 2c1a494ec69..00000000000
--- a/apps/www/app/api-v2/cms/disable-draft/route.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { draftMode } from 'next/headers'
-import { redirect } from 'next/navigation'
-import { SITE_ORIGIN } from '~/lib/constants'
-
-export async function GET(request: Request) {
- const draft = await draftMode()
- const { searchParams } = new URL(request.url)
- const slug = searchParams.get('slug')
- const path = searchParams.get('path') || 'blog'
-
- // Redirect to the path from the fetched post
- const redir = slug ? `/${path}/${slug}` : `/${path}`
-
- // Disable Draft Mode by clearing the cookie
- draft.disable()
-
- try {
- const parsed = new URL(redir, SITE_ORIGIN)
- // Only allow paths that stay on the origin
- if (parsed.origin === SITE_ORIGIN) {
- redirect(parsed.pathname)
- }
- } catch {
- // Invalid URL
- }
- redirect(SITE_ORIGIN)
-}
diff --git a/apps/www/app/api-v2/cms/preview/route.ts b/apps/www/app/api-v2/cms/preview/route.ts
deleted file mode 100644
index c0cb489e536..00000000000
--- a/apps/www/app/api-v2/cms/preview/route.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { draftMode } from 'next/headers'
-import { redirect } from 'next/navigation'
-import { SITE_ORIGIN } from '~/lib/constants'
-
-export async function GET(request: Request) {
- const draft = await draftMode()
- const { searchParams } = new URL(request.url)
- const secret = searchParams.get('secret')
- const slug = searchParams.get('slug')
- const path = searchParams.get('path') || 'blog'
-
- // Get the expected secret with fallback to match CMS configuration
- const expectedSecret = process.env.CMS_PREVIEW_SECRET
-
- if (secret !== expectedSecret) {
- console.error('[preview] Token mismatch:', {
- received: secret,
- expected: expectedSecret,
- })
- return new Response(
- `Invalid token. Expected: ${expectedSecret?.slice(0, 3)}..., Received: ${secret?.slice(0, 3)}...`,
- { status: 401 }
- )
- }
-
- if (!slug) {
- console.error('[preview] No slug provided')
- return new Response('No slug in the request', { status: 401 })
- }
-
- // Enable Draft Mode by setting the cookie
- draft.enable()
-
- // Redirect to the path from the fetched post
- const redir = `/${path}/${slug}`
-
- try {
- const parsed = new URL(redir, SITE_ORIGIN)
- // Only allow paths that stay on the origin
- if (parsed.origin === SITE_ORIGIN) {
- redirect(parsed.pathname)
- }
- } catch {
- // Invalid URL
- }
- redirect(SITE_ORIGIN)
-}
diff --git a/apps/www/app/api-v2/cms/revalidate/route.ts b/apps/www/app/api-v2/cms/revalidate/route.ts
deleted file mode 100644
index 3ff73f9e8d8..00000000000
--- a/apps/www/app/api-v2/cms/revalidate/route.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { revalidatePath } from 'next/cache'
-import { NextRequest, NextResponse } from 'next/server'
-
-export async function POST(request: NextRequest) {
- try {
- const body = await request.json()
- const { secret, path } = body
-
- // Check for secret to confirm this is a valid request
- if (secret !== process.env.CMS_PREVIEW_SECRET) {
- return NextResponse.json({ message: 'Invalid token' }, { status: 401 })
- }
-
- if (!path) {
- return NextResponse.json({ message: 'Missing path parameter' }, { status: 400 })
- }
-
- // This will revalidate the specific page
- revalidatePath(path)
-
- return NextResponse.json({ revalidated: true, path })
- } catch (error) {
- console.error('[Revalidate API] Error during revalidation:', error)
- return NextResponse.json(
- {
- message: 'Error revalidating',
- error: error instanceof Error ? error.message : 'Unknown error',
- },
- { status: 500 }
- )
- }
-}
diff --git a/apps/www/app/blog/[slug]/BlogPostClient.tsx b/apps/www/app/blog/[slug]/BlogPostClient.tsx
index 8da4126fae2..07347abd8b0 100644
--- a/apps/www/app/blog/[slug]/BlogPostClient.tsx
+++ b/apps/www/app/blog/[slug]/BlogPostClient.tsx
@@ -1,19 +1,13 @@
'use client'
import dynamic from 'next/dynamic'
-import { useState, useMemo, useEffect } from 'react'
-import { useLivePreview } from '@payloadcms/live-preview-react'
-import authors from 'lib/authors.json'
-import { CMS_SITE_ORIGIN } from 'lib/constants'
-import { isNotNullOrUndefined } from 'lib/helpers'
-import { generateTocFromMarkdown } from 'lib/toc'
-import { convertRichTextToMarkdown } from '~/lib/cms/convertRichTextToMarkdown'
-import useActiveAnchors from 'hooks/useActiveAnchors'
+import useActiveAnchors from '@/hooks/useActiveAnchors'
+import authors from '@/lib/authors.json'
+import { isNotNullOrUndefined } from '@/lib/helpers'
+import type { Blog, BlogData, PostReturnType, ProcessedBlogData } from '@/types/post'
-import type { Blog, BlogData, CMSAuthor, PostReturnType, ProcessedBlogData } from 'types/post'
-
-const BlogPostRenderer = dynamic(() => import('components/Blog/BlogPostRenderer'))
+const BlogPostRenderer = dynamic(() => import('@/components/Blog/BlogPostRenderer'))
type BlogPostPageProps = {
prevPost: PostReturnType | null
@@ -27,149 +21,27 @@ type BlogPostPageProps = {
export default function BlogPostClient(props: BlogPostPageProps) {
const isDraftMode = props.isDraftMode
- const [previewData] = useState<ProcessedBlogData>(props.blog)
// Enable scroll-to-anchor functionality and TOC highlighting
useActiveAnchors()
- const [processedToc, setProcessedToc] = useState<{ content: string; json: any[] } | null>(null)
- const shouldUseLivePreview = isDraftMode && 'isCMS' in props.blog && props.blog.isCMS
-
- const { data: livePreviewData, isLoading: isLivePreviewLoading } = useLivePreview({
- initialData: props.blog,
- serverURL: CMS_SITE_ORIGIN || 'http://localhost:3030',
- depth: 2,
- })
-
- // Generate TOC for LivePreview data when content changes
- useEffect(() => {
- if (isDraftMode && shouldUseLivePreview && livePreviewData?.content) {
- // Check if content is rich text (object) or already converted to markdown (string)
- let markdownContent = ''
- if (typeof livePreviewData.content === 'string') {
- markdownContent = livePreviewData.content
- } else if (typeof livePreviewData.content === 'object') {
- markdownContent = convertRichTextToMarkdown(livePreviewData.content)
- }
-
- if (markdownContent) {
- const tocDepth = (livePreviewData as any).toc_depth || (props.blog as any).toc_depth || 3
-
- generateTocFromMarkdown(markdownContent, tocDepth)
- .then((tocResult) => {
- setProcessedToc(tocResult)
- })
- .catch((error) => {
- console.error('Error generating TOC:', error)
- setProcessedToc(null)
- })
- }
- }
- }, [
- isDraftMode,
- shouldUseLivePreview,
- livePreviewData?.content,
- livePreviewData?.toc_depth,
- props.blog.toc_depth,
- ])
-
- const blogMetaData = useMemo(() => {
- if (isDraftMode && shouldUseLivePreview) {
- if (livePreviewData && typeof livePreviewData === 'object') {
- // Process LivePreview author data to match expected CMSAuthor structure
- const processedAuthors =
- livePreviewData.authors?.map((author: Record<string, unknown>) => {
- // Handle both direct author objects and author references
- if (typeof author === 'object' && author !== null) {
- const authorName =
- (author.author as string) || (author.name as string) || 'Unknown Author'
- const authorId = (author.author_id as string) || (author.id as string) || ''
- const position = (author.position as string) || ''
- const authorUrl = (author.author_url as string) || '#'
- const username = (author.username as string) || ''
-
- // Handle author image URL with proper type checking
- let authorImageUrl: string | null = null
- const authorImage = author.author_image_url as
- | { url?: string }
- | string
- | null
- | undefined
-
- if (authorImage) {
- if (typeof authorImage === 'string') {
- authorImageUrl = authorImage
- } else if (typeof authorImage === 'object' && authorImage.url) {
- const imageUrl = authorImage.url
- if (typeof imageUrl === 'string') {
- authorImageUrl = imageUrl.includes('http')
- ? imageUrl
- : `${CMS_SITE_ORIGIN}${imageUrl}`
- }
- }
- }
-
- return {
- author: authorName,
- author_id: authorId,
- position,
- author_url: authorUrl,
- author_image_url: authorImageUrl,
- username,
- }
- }
- return {
- author: typeof author === 'string' ? author : 'Unknown Author',
- author_id: '',
- position: '',
- author_url: '#',
- author_image_url: null,
- username: '',
- }
- }) ?? []
-
- const processedLivePreviewData = {
- ...props.blog,
- ...livePreviewData,
- authors: processedAuthors,
- // Use processed TOC if available, otherwise fall back to original
- toc: processedToc || props.blog.toc,
- toc_depth: (livePreviewData as any).toc_depth || props.blog.toc_depth || 3,
- }
- return processedLivePreviewData
- }
- if (previewData !== props.blog) {
- return previewData
- }
- }
- return props.blog
- }, [
- isDraftMode,
- shouldUseLivePreview,
- livePreviewData,
- previewData,
- props.blog,
- processedToc,
- ]) as ProcessedBlogData
-
- const isCMS = 'isCMS' in blogMetaData && blogMetaData.isCMS
+ const blogMetaData = props.blog
- const blogAuthors = isCMS
- ? ('authors' in blogMetaData ? (blogMetaData.authors as CMSAuthor[]) : []) || []
- : ('author' in blogMetaData ? (blogMetaData.author as string) : '')
- ?.split(',')
- .map((authorId: string) => {
- const foundAuthor = authors.find((author) => author.author_id === authorId)
- return foundAuthor ?? null
- })
- .filter(isNotNullOrUndefined) || []
+ const blogAuthors = (blogMetaData.author ?? '')
+ ?.split(',')
+ .map((authorId) => authorId.trim())
+ .filter(Boolean)
+ .map((authorId) => {
+ const foundAuthor = authors.find((author) => author.author_id === authorId)
+ return foundAuthor ?? null
+ })
+ .filter(isNotNullOrUndefined)
return (
<BlogPostRenderer
blog={props.blog as ProcessedBlogData}
blogMetaData={blogMetaData as ProcessedBlogData}
isDraftMode={isDraftMode}
- isLivePreviewLoading={isLivePreviewLoading}
prevPost={props.prevPost}
nextPost={props.nextPost}
authors={blogAuthors}
diff --git a/apps/www/app/blog/[slug]/page.tsx b/apps/www/app/blog/[slug]/page.tsx
index c00340d66eb..243f343da55 100644
--- a/apps/www/app/blog/[slug]/page.tsx
+++ b/apps/www/app/blog/[slug]/page.tsx
@@ -1,57 +1,13 @@
-import { getAllCMSPostSlugs, getCMSPostBySlug } from 'lib/get-cms-posts'
-import { getAllPostSlugs, getPostdata, getSortedPosts } from 'lib/posts'
import type { Metadata } from 'next'
import { draftMode } from 'next/headers'
-import type { Blog, BlogData, PostReturnType } from 'types/post'
import BlogPostClient from './BlogPostClient'
-import { processCMSContent } from '~/lib/cms/processCMSContent'
-import { CMS_SITE_ORIGIN, SITE_ORIGIN } from '~/lib/constants'
+import { SITE_ORIGIN } from '@/lib/constants'
+import { getAllPostSlugs, getPostdata, getSortedPosts } from '@/lib/posts'
+import type { Blog, BlogData, PostReturnType } from '@/types/post'
export const revalidate = 30
-// Helper function to fetch CMS post using our unified API
-async function getCMSPostFromAPI(
- slug: string,
- mode: 'preview' | 'full' = 'full',
- isDraft: boolean = false
-) {
- try {
- const url = new URL(`${SITE_ORIGIN}/api-v2/cms-posts`)
- url.searchParams.set('slug', slug)
- url.searchParams.set('mode', mode)
- if (isDraft) {
- url.searchParams.set('draft', 'true')
- }
-
- // Use different caching strategies based on draft mode
- const fetchOptions = isDraft
- ? {
- // For draft mode: always fresh data, no caching
- // cache: 'no-store' as const,
- next: { revalidate: 0 },
- }
- : {
- // For published posts: allow static generation with revalidation
- next: { revalidate: 60 }, // 1 minute
- }
-
- const response = await fetch(url.toString(), fetchOptions)
-
- if (!response.ok) {
- console.warn('[getCMSPostFromAPI] Non-OK response:', response.status)
- return null
- }
-
- const data = await response.json()
-
- return data.success ? data.post : null
- } catch (error) {
- console.warn('[getCMSPostFromAPI] Error:', error)
- return null
- }
-}
-
type MatterReturn = {
data: BlogData
content: string
@@ -71,8 +27,7 @@ type Params = {
export async function generateStaticParams() {
const staticPaths = getAllPostSlugs('_blog')
- const cmsPaths = await getAllCMSPostSlugs()
- return [...staticPaths, ...cmsPaths].map((p) => ({ slug: p.params.slug }))
+ return [...staticPaths].map((p) => ({ slug: p.params.slug }))
}
export async function generateMetadata({ params }: { params: Promise<Params> }): Promise<Metadata> {
@@ -94,11 +49,7 @@ export async function generateMetadata({ params }: { params: Promise<Params> }):
const parsedContent = matter(postContent) as unknown as MatterReturn
const blogPost = parsedContent.data
const blogImage = blogPost.imgThumb || blogPost.imgSocial
- const metaImageUrl = blogImage
- ? blogImage.startsWith('http')
- ? blogImage
- : `${CMS_SITE_ORIGIN.replace('/api-v2', '')}${blogImage}`
- : undefined
+ const metaImageUrl = blogImage && blogImage.startsWith('http') ? blogImage : undefined
return {
title: blogPost.title,
@@ -117,71 +68,10 @@ export async function generateMetadata({ params }: { params: Promise<Params> }):
images: metaImageUrl ? [metaImageUrl] : undefined,
},
}
- } catch {
- // Static post not found, try CMS post
- }
-
- // Try to fetch CMS post for metadata
- let cmsPost = await getCMSPostFromAPI(slug, 'preview', isDraft)
-
- if (!cmsPost) {
- cmsPost = await getCMSPostBySlug(slug, isDraft)
- }
-
- if (!cmsPost) {
- return {
- title: 'Blog Post Not Found',
- description: 'The requested blog post could not be found.',
- }
- }
-
- // Extract meta fields with fallbacks
- const metaTitle = cmsPost.meta?.title || cmsPost.title
- const metaDescription = cmsPost.meta?.description || cmsPost.description
-
- // Handle different image field types from CMS
- let metaImageUrl: string | undefined
- if (cmsPost.meta?.image) {
- // If meta.image is an object with url property
- if (typeof cmsPost.meta.image === 'object' && cmsPost.meta.image.url) {
- metaImageUrl = cmsPost.meta.image.url
- }
- // If meta.image is a string URL
- else if (typeof cmsPost.meta.image === 'string') {
- metaImageUrl = cmsPost.meta.image
- }
- }
-
- // Fallback to imgThumb or imgSocial if no meta image
- if (!metaImageUrl) {
- metaImageUrl = cmsPost.imgThumb || cmsPost.imgSocial
- }
-
- // Ensure image URLs are absolute
- const absoluteImageUrl = metaImageUrl
- ? metaImageUrl.startsWith('http')
- ? metaImageUrl
- : `${CMS_SITE_ORIGIN.replace('/api-v2', '')}${metaImageUrl}`
- : undefined
-
+ } catch {}
return {
- title: metaTitle,
- description: metaDescription,
- openGraph: {
- title: metaTitle,
- description: metaDescription,
- url: `${SITE_ORIGIN}/blog/${slug}`,
- type: 'article',
- publishedTime: cmsPost.date || cmsPost.publishedAt,
- authors: cmsPost.authors?.map((author: any) => author.author || 'Unknown Author'),
- images: absoluteImageUrl ? [{ url: absoluteImageUrl }] : undefined,
- },
- twitter: {
- card: 'summary_large_image',
- title: metaTitle,
- description: metaDescription,
- images: absoluteImageUrl ? [absoluteImageUrl] : undefined,
- },
+ title: 'Blog Post Not Found',
+ description: 'The requested blog post could not be found.',
}
}
@@ -246,96 +136,4 @@ export default async function BlogPostPage({ params }: { params: Promise<Params>
return <BlogPostClient {...props} />
} catch {}
-
- // Try to fetch CMS post using our new unified API first
- let cmsPost = await getCMSPostFromAPI(slug, 'full', isDraft)
-
- // Fallback to the original method if the API doesn't return the post
- if (!cmsPost) {
- cmsPost = await getCMSPostBySlug(slug, isDraft)
- }
-
- if (!cmsPost) {
- if (isDraft) {
- // Try to fetch published version for draft mode
- let publishedPost = await getCMSPostFromAPI(slug, 'full', false)
- if (!publishedPost) {
- publishedPost = await getCMSPostBySlug(slug, false)
- }
-
- if (!publishedPost) return null
-
- const mdxSource = await mdxSerialize(publishedPost.content || '', {
- tocDepth: publishedPost.toc_depth || 3,
- })
- const tocResult = (mdxSource as any).scope?.toc || publishedPost.toc || { content: '' }
- const props: BlogPostPageProps = {
- prevPost: null,
- nextPost: null,
- relatedPosts: [],
- blog: {
- ...publishedPost,
- slug: publishedPost.slug ?? slug,
- tags: publishedPost.tags || [],
- authors: publishedPost.authors || [],
- isCMS: true,
- content: mdxSource,
- toc: tocResult,
- imgSocial: publishedPost.imgSocial ?? undefined,
- imgThumb: publishedPost.imgThumb ?? undefined,
- // Extract meta fields from CMS
- meta_title: publishedPost.meta?.title ?? undefined,
- meta_description: publishedPost.meta?.description ?? undefined,
- meta_image: publishedPost.meta?.image ?? publishedPost.imgThumb ?? undefined,
- } as any,
- isDraftMode: isDraft,
- }
- return <BlogPostClient {...props} />
- }
- return null
- }
-
- const tocDepth = cmsPost.toc_depth || 3
-
- // Use the new CMS content processor to handle blocks
- let processedContent: any
-
- try {
- processedContent = await processCMSContent(cmsPost.richContent || cmsPost.content, tocDepth)
- } catch (error) {
- console.warn('Error processing CMS content, falling back to legacy processing:', error)
- // Fallback to legacy processing
- const mdxSource = await mdxSerialize(cmsPost.content || '', { tocDepth })
- processedContent = {
- content: mdxSource,
- blocks: [],
- toc: (mdxSource as any).scope?.toc || cmsPost.toc || { content: '' },
- plainMarkdown: cmsPost.content || '',
- }
- }
-
- const props: BlogPostPageProps = {
- prevPost: null,
- nextPost: null,
- relatedPosts: [],
- blog: {
- ...cmsPost,
- slug: cmsPost.slug ?? slug,
- tags: cmsPost.tags || [],
- authors: cmsPost.authors || [],
- isCMS: true,
- content: processedContent.content,
- toc: processedContent.toc,
- toc_depth: cmsPost.toc_depth || 3,
- imgSocial: cmsPost.imgSocial ?? undefined,
- imgThumb: cmsPost.imgThumb ?? undefined,
- // Extract meta fields from CMS
- meta_title: cmsPost.meta?.title ?? undefined,
- meta_description: cmsPost.meta?.description ?? undefined,
- meta_image: cmsPost.meta?.image ?? cmsPost.imgThumb ?? undefined,
- } as any,
- isDraftMode: isDraft,
- }
-
- return <BlogPostClient {...props} />
}
diff --git a/apps/www/app/blog/authors/[author]/page.tsx b/apps/www/app/blog/authors/[author]/page.tsx
index 29297b45bb7..a60a1ea5272 100644
--- a/apps/www/app/blog/authors/[author]/page.tsx
+++ b/apps/www/app/blog/authors/[author]/page.tsx
@@ -1,10 +1,9 @@
import type { Metadata } from 'next'
-import blogAuthors from 'lib/authors.json'
-import { getAllCMSPosts } from 'lib/get-cms-posts'
-import { getSortedPosts } from 'lib/posts'
-import type PostTypes from 'types/post'
import AuthorClient from './AuthorClient'
+import blogAuthors from '@/lib/authors.json'
+import { getSortedPosts } from '@/lib/posts'
+import type PostTypes from '@/types/post'
type Params = { author: string }
@@ -55,15 +54,7 @@ export default async function AuthorPage({ params: paramsPromise }: { params: Pr
return postAuthors.some((a: string) => toCanonicalAuthorId(a) === authorId)
})
- // Get CMS posts by this author (normalize identifiers)
- const allCmsPosts = await getAllCMSPosts({})
- const cmsPosts = allCmsPosts.filter((post: any) => {
- return post.authors?.some(
- (a: any) => toCanonicalAuthorId(a.author_id ?? a.username ?? '') === authorId
- )
- })
-
- const blogs = [...(staticPosts as any[]), ...(cmsPosts as any[])].sort(
+ const blogs = [...(staticPosts as any[])].sort(
(a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
) as unknown as PostTypes[]
diff --git a/apps/www/app/blog/categories/[category]/page.tsx b/apps/www/app/blog/categories/[category]/page.tsx
index 78dbaf46109..991c68f5515 100644
--- a/apps/www/app/blog/categories/[category]/page.tsx
+++ b/apps/www/app/blog/categories/[category]/page.tsx
@@ -1,12 +1,11 @@
import type { Metadata } from 'next'
import Link from 'next/link'
-import DefaultLayout from 'components/Layouts/Default'
-import BlogGridItem from 'components/Blog/BlogGridItem'
-import { getAllCMSPosts } from 'lib/get-cms-posts'
-import { capitalize } from 'lib/helpers'
-import { getSortedPosts, getAllCategories } from 'lib/posts'
-import type PostTypes from 'types/post'
+import BlogGridItem from '@/components/Blog/BlogGridItem'
+import DefaultLayout from '@/components/Layouts/Default'
+import { capitalize } from '@/lib/helpers'
+import { getAllCategories, getSortedPosts } from '@/lib/posts'
+import type PostTypes from '@/types/post'
type Params = { category: string }
@@ -44,11 +43,7 @@ export default async function CategoriesPage({
limit: 0,
categories: [params.category],
})
- const cmsPosts = await getAllCMSPosts()
- const blogs = [
- ...(staticPosts as any[]),
- ...(cmsPosts as any[]).filter((p) => (p.categories || []).includes(params.category)),
- ] as unknown as PostTypes[]
+ const blogs = [...staticPosts] as PostTypes[]
const capitalizedCategory = capitalize(params?.category.replaceAll('-', ' '))
return (
diff --git a/apps/www/app/blog/page.tsx b/apps/www/app/blog/page.tsx
index f4faeba9282..0b9acac73a5 100644
--- a/apps/www/app/blog/page.tsx
+++ b/apps/www/app/blog/page.tsx
@@ -1,8 +1,8 @@
-import BlogClient from './BlogClient'
-import { getSortedPosts } from 'lib/posts'
-import { getAllCMSPosts } from 'lib/get-cms-posts'
import type { Metadata } from 'next'
+import BlogClient from './BlogClient'
+import { getSortedPosts } from '@/lib/posts'
+
export const revalidate = 30
export const metadata: Metadata = {
@@ -22,11 +22,8 @@ export default async function BlogPage() {
// Get static blog posts
const staticPostsData = getSortedPosts({ directory: '_blog', runner: '** BLOG PAGE **' })
- // Get CMS posts server-side with revalidation
- const cmsPostsData = await getAllCMSPosts({ limit: 100 })
-
- // Combine static and CMS posts and sort by date
- const allPosts = [...staticPostsData, ...cmsPostsData].sort((a: any, b: any) => {
+ // Sort by date
+ const allPosts = [...staticPostsData].sort((a, b) => {
const dateA = new Date(a.date || a.formattedDate).getTime()
const dateB = new Date(b.date || b.formattedDate).getTime()
return dateB - dateA
diff --git a/apps/www/app/blog/tags/[tag]/page.tsx b/apps/www/app/blog/tags/[tag]/page.tsx
index db30a65a2d8..54449d967c4 100644
--- a/apps/www/app/blog/tags/[tag]/page.tsx
+++ b/apps/www/app/blog/tags/[tag]/page.tsx
@@ -1,12 +1,11 @@
import type { Metadata } from 'next'
import Link from 'next/link'
-import DefaultLayout from 'components/Layouts/Default'
-import BlogGridItem from 'components/Blog/BlogGridItem'
-import { getAllCMSPosts } from 'lib/get-cms-posts'
-import { capitalize } from 'lib/helpers'
-import { getSortedPosts, getAllTags } from 'lib/posts'
-import type PostTypes from 'types/post'
+import BlogGridItem from '@/components/Blog/BlogGridItem'
+import DefaultLayout from '@/components/Layouts/Default'
+import { capitalize } from '@/lib/helpers'
+import { getAllTags, getSortedPosts } from '@/lib/posts'
+import type PostTypes from '@/types/post'
type Params = { tag: string }
@@ -36,8 +35,7 @@ export default async function TagPage({ params: paramsPromise }: { params: Promi
const params = await paramsPromise
const staticPosts = getSortedPosts({ directory: '_blog', limit: 0, tags: [params.tag] })
- const cmsPosts = await getAllCMSPosts({ tags: [params.tag] })
- const blogs = [...(staticPosts as any[]), ...(cmsPosts as any[])] as unknown as PostTypes[]
+ const blogs = [...staticPosts] as PostTypes[]
const capitalizedTag = capitalize(params?.tag.replaceAll('-', ' '))
return (
diff --git a/apps/www/components/Blog/BlogGridItem.tsx b/apps/www/components/Blog/BlogGridItem.tsx
index ddaa0bddc4e..8489fe4d785 100644
--- a/apps/www/components/Blog/BlogGridItem.tsx
+++ b/apps/www/components/Blog/BlogGridItem.tsx
@@ -1,10 +1,10 @@
import dayjs from 'dayjs'
-import authors from 'lib/authors.json'
import Image from 'next/image'
import Link from 'next/link'
-import type Author from '~/types/author'
-import type PostTypes from '~/types/post'
+import authors from '@/lib/authors.json'
+import type Author from '@/types/author'
+import type PostTypes from '@/types/post'
interface Props {
post: PostTypes
@@ -29,11 +29,10 @@ const BlogGridItem = ({ post }: Props) => {
return img.startsWith('/') || img.startsWith('http') ? img : `/images/blog/${img}`
}
- const imageUrl = post.isCMS
- ? post.imgThumb || post.imgSocial || '/images/blog/blog-placeholder.png'
- : resolveImagePath(post.imgThumb) ||
- resolveImagePath(post.imgSocial) ||
- '/images/blog/blog-placeholder.png'
+ const imageUrl =
+ resolveImagePath(post.imgThumb) ||
+ resolveImagePath(post.imgSocial) ||
+ '/images/blog/blog-placeholder.png'
return (
<Link
diff --git a/apps/www/components/Blog/BlogListItem.tsx b/apps/www/components/Blog/BlogListItem.tsx
index deec2f87cb4..d5b19ae748d 100644
--- a/apps/www/components/Blog/BlogListItem.tsx
+++ b/apps/www/components/Blog/BlogListItem.tsx
@@ -1,31 +1,17 @@
-import blogAuthors from 'lib/authors.json'
+import dayjs from 'dayjs'
import Image from 'next/image'
import Link from 'next/link'
import React from 'react'
-import type PostTypes from '~/types/post'
-import dayjs from 'dayjs'
import { Badge } from 'ui'
-import type { CMSPostTypes } from '~/types/post'
+
+import blogAuthors from '@/lib/authors.json'
+import type PostTypes from '@/types/post'
interface Props {
- post: PostTypes | CMSPostTypes
+ post: PostTypes
}
-const getAuthors = (post: PostTypes | CMSPostTypes) => {
- if ('isCMS' in post && post.isCMS) {
- // For CMS posts, display author directly from the blog data
- const cmsBlog = post as CMSPostTypes
- const authors =
- cmsBlog.authors?.map((author) => ({
- author: author.author || 'Unknown Author',
- author_image_url: author.author_image_url || null,
- author_url: author.author_url || '#',
- position: author.position || '',
- })) || []
-
- return authors
- }
-
+const getAuthors = (post: PostTypes) => {
const authorArray = post.author?.split(',').map((a) => a.trim()) || []
const authors = []
diff --git a/apps/www/components/Blog/BlogPostRenderer.tsx b/apps/www/components/Blog/BlogPostRenderer.tsx
index f718e8d0a2e..395610377ad 100644
--- a/apps/www/components/Blog/BlogPostRenderer.tsx
+++ b/apps/www/components/Blog/BlogPostRenderer.tsx
@@ -1,7 +1,6 @@
'use client'
import dayjs from 'dayjs'
-import mdxComponents from 'lib/mdx/mdxComponents'
import { ChevronLeft } from 'lucide-react'
import { MDXRemote } from 'next-mdx-remote'
import type { MDXRemoteSerializeResult } from 'next-mdx-remote'
@@ -10,20 +9,22 @@ import Image from 'next/image'
import Link from 'next/link'
import { useMemo, useState } from 'react'
import type { ComponentType } from 'react'
-import type { CMSAuthor, PostReturnType, ProcessedBlogData, Tag } from 'types/post'
+import type { PostReturnType, ProcessedBlogData, StaticAuthor, Tag } from 'types/post'
import { Badge } from 'ui'
-const ShareArticleActions = dynamic(() => import('components/Blog/ShareArticleActions'))
-const CTABanner = dynamic(() => import('components/CTABanner'))
-const LW11Summary = dynamic(() => import('components/LaunchWeek/11/LW11Summary'))
-const LW12Summary = dynamic(() => import('components/LaunchWeek/12/LWSummary'))
-const LW13Summary = dynamic(() => import('components/LaunchWeek/13/Releases/LWSummary'))
-const LW14Summary = dynamic(() => import('components/LaunchWeek/14/Releases/LWSummary'))
-const LW15Summary = dynamic(() => import('components/LaunchWeek/15/LWSummary'))
-const BlogLinks = dynamic(() => import('components/LaunchWeek/7/BlogLinks'))
-const LWXSummary = dynamic(() => import('components/LaunchWeek/X/LWXSummary'))
-const DefaultLayout = dynamic(() => import('components/Layouts/Default'))
-const DraftModeBanner = dynamic(() => import('components/Blog/DraftModeBanner'))
+import mdxComponents from '@/lib/mdx/mdxComponents'
+
+const ShareArticleActions = dynamic(() => import('@/components/Blog/ShareArticleActions'))
+const CTABanner = dynamic(() => import('@/components/CTABanner'))
+const LW11Summary = dynamic(() => import('@/components/LaunchWeek/11/LW11Summary'))
+const LW12Summary = dynamic(() => import('@/components/LaunchWeek/12/LWSummary'))
+const LW13Summary = dynamic(() => import('@/components/LaunchWeek/13/Releases/LWSummary'))
+const LW14Summary = dynamic(() => import('@/components/LaunchWeek/14/Releases/LWSummary'))
+const LW15Summary = dynamic(() => import('@/components/LaunchWeek/15/LWSummary'))
+const BlogLinks = dynamic(() => import('@/components/LaunchWeek/7/BlogLinks'))
+const LWXSummary = dynamic(() => import('@/components/LaunchWeek/X/LWXSummary'))
+const DefaultLayout = dynamic(() => import('@/components/Layouts/Default'))
+const DraftModeBanner = dynamic(() => import('@/components/Blog/DraftModeBanner'))
const ReactMarkdown = dynamic<{ children: string }>(
() =>
import('react-markdown').then(
@@ -36,7 +37,6 @@ const BlogPostRenderer = ({
blog,
blogMetaData,
isDraftMode,
- livePreviewData,
prevPost,
nextPost,
authors,
@@ -44,43 +44,18 @@ const BlogPostRenderer = ({
blog: ProcessedBlogData
blogMetaData: ProcessedBlogData
isDraftMode: boolean
- livePreviewData?: ProcessedBlogData
- isLivePreviewLoading?: boolean
prevPost?: PostReturnType | null
nextPost?: PostReturnType | null
- authors: CMSAuthor[]
+ authors: StaticAuthor[]
}) => {
const [previewData] = useState<ProcessedBlogData>(blog)
- const shouldUseLivePreview = isDraftMode && blog.isCMS
-
// For LivePreview, we'll use the raw content directly with ReactMarkdown
// instead of trying to use MDXRemote which requires specific serialization
- const isLivePreview = isDraftMode && (livePreviewData !== undefined || previewData !== blog)
+ const isLivePreview = isDraftMode && previewData !== blog
// Extract raw content from data if available
const livePreviewContent = useMemo(() => {
- // Priority 1: Use data from LivePreview hook (only in draft mode)
- if (
- isDraftMode &&
- shouldUseLivePreview &&
- livePreviewData &&
- typeof livePreviewData === 'object'
- ) {
- // If content is a string, use it directly
- if (typeof (livePreviewData as unknown as { content?: unknown }).content === 'string') {
- return (livePreviewData as unknown as { content?: string }).content as string
- }
-
- // If content is from source property
- if (
- (livePreviewData as unknown as { source?: unknown }).source &&
- typeof (livePreviewData as unknown as { source?: unknown }).source === 'string'
- ) {
- return (livePreviewData as unknown as { source?: string }).source as string
- }
- }
-
// Priority 2: Use data from postMessage updates
if (isDraftMode && previewData !== blog) {
// If content is a string, use it directly
@@ -98,9 +73,8 @@ const BlogPostRenderer = ({
}
return blog.source || ''
- }, [isDraftMode, shouldUseLivePreview, livePreviewData, previewData, blog])
+ }, [isDraftMode, previewData, blog])
- const isCMS = blogMetaData.isCMS
const isLaunchWeek7 = blogMetaData.launchweek === '7'
const isLaunchWeekX = blogMetaData.launchweek?.toString().toLocaleLowerCase() === 'x'
const isGAWeek = blogMetaData.launchweek?.toString().toLocaleLowerCase() === '11'
@@ -157,13 +131,11 @@ const BlogPostRenderer = ({
</div>
)
- const imageUrl = isCMS
- ? blogMetaData.imgThumb ?? ''
- : blogMetaData.imgThumb
- ? blogMetaData.imgThumb.startsWith('/') || blogMetaData.imgThumb.startsWith('http')
- ? blogMetaData.imgThumb
- : `/images/blog/${blogMetaData.imgThumb}`
- : ''
+ const imageUrl = blogMetaData.imgThumb
+ ? blogMetaData.imgThumb.startsWith('/') || blogMetaData.imgThumb.startsWith('http')
+ ? blogMetaData.imgThumb
+ : `/images/blog/${blogMetaData.imgThumb}`
+ : ''
return (
<>
@@ -203,11 +175,7 @@ const BlogPostRenderer = ({
<div className="flex justify-between">
<div className="flex-1 flex flex-wrap gap-3 pt-2 md:gap-0 lg:gap-3">
{authors.map((author, i: number) => {
- // Handle both static and CMS author image formats
- const authorImageUrl =
- typeof author.author_image_url === 'string'
- ? author.author_image_url
- : (author.author_image_url as { url: string })?.url || ''
+ const authorImageUrl = author.author_image_url
const authorId =
(author as any).author_id ||
diff --git a/apps/www/components/Blog/DraftModeBanner.tsx b/apps/www/components/Blog/DraftModeBanner.tsx
index edc80e73fe8..d96eed0d065 100644
--- a/apps/www/components/Blog/DraftModeBanner.tsx
+++ b/apps/www/components/Blog/DraftModeBanner.tsx
@@ -22,16 +22,6 @@ function DraftModeBanner({ onDismiss }: DraftModeBannerProps) {
</span>
</p>
</div>
- <div className="order-3 mt-2 flex-shrink-0 w-full sm:order-2 sm:mt-0 sm:w-auto">
- <Button asChild type="secondary">
- <Link
- href="/api-v2/cms/disable-draft"
- className="flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm"
- >
- Exit Draft Mode
- </Link>
- </Button>
- </div>
{onDismiss && (
<div className="order-2 flex-shrink-0 sm:order-3 sm:ml-3">
<button
diff --git a/apps/www/components/Blog/FeaturedThumb.tsx b/apps/www/components/Blog/FeaturedThumb.tsx
index 70da78732c9..0fc6b6e52f3 100644
--- a/apps/www/components/Blog/FeaturedThumb.tsx
+++ b/apps/www/components/Blog/FeaturedThumb.tsx
@@ -1,39 +1,10 @@
-import authors from 'lib/authors.json'
import Image from 'next/image'
import Link from 'next/link'
-import type PostTypes from 'types/post'
-// Extend PostTypes for CMS blog posts
-interface CMSPostTypes extends PostTypes {
- isCMS?: boolean
- authors?: Array<{
- author: string
- author_id: string
- position: string
- author_url: string
- author_image_url: {
- url: string
- }
- username: string
- }>
-}
-
-function FeaturedThumb(blog: PostTypes | CMSPostTypes) {
- // First check if this is a CMS post
- if ('isCMS' in blog && blog.isCMS) {
- // For CMS posts, display author directly from the blog data
- const cmsBlog = blog as CMSPostTypes
- const author =
- cmsBlog.authors?.map((author) => ({
- author: author.author || 'Unknown Author',
- author_image_url: author.author_image_url || null,
- author_url: author.author_url || '#',
- position: author.position || '',
- })) || []
-
- return renderFeaturedThumb(blog, author)
- }
+import authors from '@/lib/authors.json'
+import type PostTypes from '@/types/post'
+function FeaturedThumb(blog: PostTypes) {
// For static posts, look up author info from authors.json
const authorArray = blog.author?.split(',').map((a) => a.trim()) || []
const author = []
@@ -56,11 +27,10 @@ function renderFeaturedThumb(blog: PostTypes, author: any[]) {
return img.startsWith('/') || img.startsWith('http') ? img : `/images/blog/${img}`
}
- const imageUrl = blog.isCMS
- ? blog.imgThumb || blog.imgSocial || '/images/blog/blog-placeholder.png'
- : resolveImagePath(blog.imgThumb) ||
- resolveImagePath(blog.imgSocial) ||
- '/images/blog/blog-placeholder.png'
+ const imageUrl =
+ resolveImagePath(blog.imgThumb) ||
+ resolveImagePath(blog.imgSocial) ||
+ '/images/blog/blog-placeholder.png'
return (
<div key={blog.slug} className="w-full">
diff --git a/apps/www/internals/generate-sitemap.mjs b/apps/www/internals/generate-sitemap.mjs
index f8231787875..c9ac6349b8f 100644
--- a/apps/www/internals/generate-sitemap.mjs
+++ b/apps/www/internals/generate-sitemap.mjs
@@ -2,63 +2,6 @@ import { writeFileSync } from 'fs'
import { globby } from 'globby'
import prettier from 'prettier'
-/*
- * kudos to leerob from vercel
- * https://leerob.io/blog/nextjs-sitemap-robots
- */
-
-// Constants for CMS integration
-const CMS_SITE_ORIGIN =
- process.env.NEXT_PUBLIC_VERCEL_ENV === 'production'
- ? 'https://cms.supabase.com'
- : process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL &&
- typeof process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL === 'string'
- ? `https://${process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL?.replace('zone-www-dot-com-git-', 'cms-git-')}`
- : 'http://localhost:3030'
-const CMS_API_KEY = process.env.CMS_API_KEY
-
-/**
- * Get CMS blog posts for sitemap
- */
-const getCMSBlogPosts = async () => {
- try {
- const response = await fetch(
- `${CMS_SITE_ORIGIN}/api/posts?depth=0&draft=false&where[_status][equals]=published&limit=1000`,
- {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- }
- )
-
- if (!response.ok) {
- console.warn(`[getCMSBlogPosts] HTTP error! status: ${response.status}`)
- return []
- }
-
- const contentType = response.headers.get('content-type') || ''
- if (!contentType.toLowerCase().includes('application/json')) {
- console.warn(`[getCMSBlogPosts] Non-JSON response from CMS`)
- return []
- }
-
- const data = await response.json()
-
- const posts = data.docs
- .filter((post) => post.slug && post.title && post._status === 'published')
- .map((post) => ({
- slug: post.slug,
- updatedAt: post.updatedAt || new Date().toISOString(),
- }))
-
- return posts
- } catch (error) {
- console.warn('Error fetching CMS blog posts for sitemap:', error)
- return []
- }
-}
-
async function generate() {
const prettierConfig = await prettier.resolveConfig('./.prettierrc.js')
@@ -85,10 +28,6 @@ async function generate() {
const pages = unsortedPages.sort((a, b) => a.localeCompare(b))
- // Fetch CMS blog posts
- const cmsBlogPosts = await getCMSBlogPosts()
- console.log(`Found ${cmsBlogPosts.length} CMS blog posts for sitemap`)
-
const blogUrl = 'blog'
const caseStudiesUrl = 'case-studies'
const customerStoriesUrl = 'customers'
@@ -176,23 +115,10 @@ async function generate() {
})
.filter(Boolean)
- // Generate URLs for CMS blog posts
- const cmsBlogUrls = cmsBlogPosts.map((post) => {
- const lastmod = new Date(post.updatedAt).toISOString().split('T')[0]
- return `
- <url>
- <loc>https://supabase.com/blog/${post.slug}</loc>
- <lastmod>${lastmod}</lastmod>
- <changefreq>weekly</changefreq>
- <priority>0.7</priority>
- </url>
- `
- })
-
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
- ${[...staticUrls, ...cmsBlogUrls].join('')}
+ ${[...staticUrls].join('')}
</urlset>
`
diff --git a/apps/www/lib/cms/README.md b/apps/www/lib/cms/README.md
deleted file mode 100644
index 0d189c17ba9..00000000000
--- a/apps/www/lib/cms/README.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# CMS Block Integration
-
-This directory contains utilities for integrating PayloadCMS custom blocks with the www marketing site blog.
-
-## Overview
-
-PayloadCMS blog posts can contain custom blocks (Banner, MediaBlock, Code, Quote, YouTube) in addition to regular text content. This integration converts those blocks into the existing markdown/MDX syntax that the www blog already understands, ensuring seamless compatibility.
-
-## Components
-
-### convertRichTextToMarkdown.ts
-
-Enhanced conversion utilities:
-
-- `convertRichTextToMarkdownWithBlocks()` - Converts PayloadCMS rich text to markdown using existing www syntax
-- `convertRichTextToMarkdown()` - Legacy function for backward compatibility
-
-### processCMSContent.ts
-
-Main processor that:
-
-1. Converts PayloadCMS rich text to markdown using existing www component syntax
-2. Generates table of contents from the converted content
-3. Serializes content for MDX rendering
-
-## Usage
-
-### In Blog Pages
-
-```typescript
-import { processCMSContent } from '~/lib/cms/processCMSContent'
-
-// Process CMS content - blocks are converted to existing www syntax
-const processedContent = await processCMSContent(cmsPost.content, tocDepth)
-
-// Use in blog data
-const blogData = {
- ...cmsPost,
- content: processedContent.content, // MDX with existing www components
- toc: processedContent.toc,
-}
-```
-
-### Block Conversion Examples
-
-PayloadCMS blocks are automatically converted to existing www markdown syntax:
-
-````typescript
-// PayloadCMS MediaBlock becomes:
-'<Img alt="Description" src="/uploads/image.jpg" />'
-
-// PayloadCMS Code block becomes:
-'```typescript\nconst example = "Hello world"\n```'
-
-// PayloadCMS Quote block becomes:
-'<Quote img="avatar.jpg" caption="Author Name">\n\nQuote text here\n\n</Quote>'
-
-// PayloadCMS YouTube block becomes:
-'<div className="video-container">\n <iframe src="..." />\n</div>'
-
-// PayloadCMS Banner block becomes:
-'<Admonition type="note">\n\nBanner content\n\n</Admonition>'
-````
-
-## Block Type Mapping
-
-| PayloadCMS Block | WWW Syntax | Notes |
-| ---------------- | ----------------------------------- | ------------------------------------------------------------------------- |
-| `banner` | `<Admonition>` | Style mapped: info→note, warning→warning, error→destructive, success→note |
-| `mediaBlock` | `<Img>` | Handles CMS image URLs and captions |
-| `code` | `code` | Standard markdown code blocks with language syntax highlighting |
-| `quote` | `<Quote>` | Avatar image and caption support |
-| `youtube` | `<div className="video-container">` | Wrapped iframe with expected styling |
-
-## Environment Variables
-
-- `NEXT_PUBLIC_CMS_SITE_ORIGIN` - Used for resolving relative CMS image URLs
-
-## Integration Points
-
-1. **apps/www/app/blog/[slug]/page.tsx** - Uses `processCMSContent()` to convert CMS content
-2. **apps/www/app/blog/[slug]/BlogPostClient.tsx** - Handles live preview with block conversion
-3. **apps/www/lib/get-cms-posts.tsx** - Uses shared conversion utilities for consistent processing
-
-This system allows PayloadCMS editors to use rich blocks while maintaining 100% compatibility with the existing MDX-based blog rendering system. No new components or special handling is required - blocks are seamlessly converted to the markdown/MDX syntax that www already understands.
diff --git a/apps/www/lib/cms/convertRichTextToMarkdown.ts b/apps/www/lib/cms/convertRichTextToMarkdown.ts
deleted file mode 100644
index 6b8fb206af9..00000000000
--- a/apps/www/lib/cms/convertRichTextToMarkdown.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-import { CMS_SITE_ORIGIN } from '../constants'
-
-// Define minimal block structure for compatibility
-type CMSBlock = {
- blockType: string
- [key: string]: any
-}
-
-/**
- * Enhanced convert function that handles both text nodes and custom blocks
- * Converts CMS blocks into existing www markdown syntax
- */
-export function convertRichTextToMarkdownWithBlocks(content: any): {
- markdown: string
- blocks: CMSBlock[]
-} {
- if (!content?.root?.children) return { markdown: '', blocks: [] }
-
- const blocks: CMSBlock[] = []
-
- const markdown = content.root.children
- .map((node: any) => {
- // Handle basic text nodes
- if (node.type === 'heading') {
- const level = node.tag && typeof node.tag === 'string' ? node.tag.replace('h', '') : '1'
- const text = node.children?.map((child: any) => child.text).join('') || ''
- return `${'#'.repeat(Number(level))} ${text}`
- }
-
- if (node.type === 'paragraph') {
- return node.children?.map((child: any) => child.text).join('') || ''
- }
-
- if (node.type === 'list') {
- const items = node.children
- ?.map((item: any) => {
- if (item.type === 'list-item') {
- return `- ${item.children?.map((child: any) => child.text).join('') || ''}`
- }
- return ''
- })
- .filter(Boolean)
- .join('\n')
- return items
- }
-
- if (node.type === 'link') {
- const text = node.children?.map((child: any) => child.text).join('') || ''
- const url = node.url || ''
- return `[${text}](${url})`
- }
-
- // Handle custom blocks - convert to existing www markdown syntax
- if (node.type === 'block') {
- const blockType = node.fields?.blockType
-
- switch (blockType) {
- case 'banner': {
- // Convert banner to Admonition
- const style = node.fields.style || 'info'
- const content = extractTextFromField(node.fields.content)
- const typeMap = {
- info: 'note',
- warning: 'warning',
- error: 'destructive',
- success: 'note',
- } as const
- return `<Admonition type="${typeMap[style as keyof typeof typeMap] || 'note'}">\n\n${content}\n\n</Admonition>`
- }
-
- case 'mediaBlock': {
- // Convert mediaBlock to Img component
- const media = node.fields.media
- if (typeof media === 'object' && media.url) {
- const imageUrl = `${CMS_SITE_ORIGIN}${media.url}` // Coming from the CMS app
- const alt = extractTextFromField(media.alt)
- const caption = extractTextFromField(media.caption)
-
- let imgComponent = ''
-
- if (caption) {
- imgComponent = `<Img alt="${alt}" src="${imageUrl}" caption="${caption}" />`
- } else {
- imgComponent = `<Img alt="${alt}" src="${imageUrl}" />`
- }
-
- return imgComponent
- }
- return ''
- }
-
- case 'code': {
- // Convert code block to markdown code block
- const language = node.fields.language || 'text'
- const code = node.fields.code || ''
- return `\`\`\`${language}\n${code}\n\`\`\``
- }
-
- case 'quote': {
- // Convert quote to Quote component
- const text = extractTextFromField(node.fields.text)
- const caption = extractTextFromField(node.fields.caption)
-
- const img = node.fields.img
-
- let imgProp = ''
- if (typeof img === 'object' && img?.url) {
- const imageUrl = `${CMS_SITE_ORIGIN}${img.url}`
-
- imgProp = ` img="${imageUrl}"`
- }
-
- const captionProp = caption ? ` caption="${caption}"` : ''
-
- return `<Quote${imgProp}${captionProp}>\n${text}\n</Quote>`
- }
-
- case 'youtube': {
- // Convert YouTube to video-container div with iframe
- const youtubeId = node.fields.youtubeId || ''
- return `<div className="video-container">
- <iframe
- className="w-full"
- src="https://www.youtube-nocookie.com/embed/${youtubeId}"
- title="YouTube video player"
- allow="accelerometer; autoplay; clipboard-write; encrypted-media; fullscreen; gyroscope; picture-in-picture; web-share"
- allowfullscreen
- />
-</div>`
- }
-
- default:
- console.warn('Unknown block type:', blockType)
- return ''
- }
- }
-
- return ''
- })
- .filter(Boolean)
- .join('\n\n')
-
- return { markdown, blocks }
-}
-
-/**
- * Helper function to extract text from either a string or rich text object
- */
-function extractTextFromField(field: any): string {
- if (!field) return ''
-
- if (typeof field === 'string') {
- return field
- }
-
- if (typeof field === 'object') {
- return convertSimpleRichTextToPlainText(field)
- }
-
- return ''
-}
-
-/**
- * Convert simple rich text content to plain text (for banner content)
- */
-function convertSimpleRichTextToPlainText(content: any): string {
- if (!content?.root?.children) return ''
-
- return content.root.children
- .map((node: any) => {
- if (node.type === 'paragraph') {
- return node.children?.map((child: any) => child.text).join('') || ''
- }
-
- if (node.type === 'heading') {
- const text = node.children?.map((child: any) => child.text).join('') || ''
- return text
- }
-
- return ''
- })
- .filter(Boolean)
- .join('\n\n')
-}
-
-/**
- * Convert simple rich text content (like banner content) to HTML
- */
-function convertSimpleRichTextToHTML(content: any): string {
- if (!content?.root?.children) return ''
-
- return content.root.children
- .map((node: any) => {
- if (node.type === 'paragraph') {
- const text =
- node.children
- ?.map((child: any) => {
- if (child.bold) return `<strong>${child.text}</strong>`
- if (child.italic) return `<em>${child.text}</em>`
- if (child.code) return `<code>${child.text}</code>`
- return child.text
- })
- .join('') || ''
- return `<p>${text}</p>`
- }
-
- if (node.type === 'heading') {
- const level = node.tag && typeof node.tag === 'string' ? node.tag.replace('h', '') : '2'
- const text = node.children?.map((child: any) => child.text).join('') || ''
- return `<h${level}>${text}</h${level}>`
- }
-
- return ''
- })
- .filter(Boolean)
- .join('')
-}
-
-/**
- * Legacy function for backward compatibility - converts to plain markdown without blocks
- */
-export function convertRichTextToMarkdown(content: any): string {
- if (!content?.root?.children) return ''
-
- return content.root.children
- .map((node: any) => {
- if (node.type === 'heading') {
- const level = node.tag && typeof node.tag === 'string' ? node.tag.replace('h', '') : '1'
- const text = node.children?.map((child: any) => child.text).join('') || ''
- return `${'#'.repeat(Number(level))} ${text}`
- }
- if (node.type === 'paragraph') {
- return node.children?.map((child: any) => child.text).join('') || ''
- }
- if (node.type === 'list') {
- const items = node.children
- ?.map((item: any) => {
- if (item.type === 'list-item') {
- return `- ${item.children?.map((child: any) => child.text).join('') || ''}`
- }
- return ''
- })
- .filter(Boolean)
- .join('\n')
- return items
- }
- if (node.type === 'link') {
- const text = node.children?.map((child: any) => child.text).join('') || ''
- const url = node.url || ''
- return `[${text}](${url})`
- }
-
- // For blocks, just return placeholder text for TOC generation
- if (node.type === 'block') {
- const blockType = node.fields?.blockType
- switch (blockType) {
- case 'code':
- return `\`\`\`${node.fields.language || ''}\n${node.fields.code || ''}\n\`\`\``
- case 'quote':
- return `> ${node.fields.text || ''}`
- default:
- return ''
- }
- }
-
- return ''
- })
- .filter(Boolean)
- .join('\n\n')
-}
diff --git a/apps/www/lib/cms/processCMSContent.ts b/apps/www/lib/cms/processCMSContent.ts
deleted file mode 100644
index 06526429be7..00000000000
--- a/apps/www/lib/cms/processCMSContent.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { MDXRemoteSerializeResult } from 'next-mdx-remote'
-import {
- convertRichTextToMarkdownWithBlocks,
- convertRichTextToMarkdown,
-} from './convertRichTextToMarkdown'
-import { generateTocFromMarkdown } from '~/lib/toc'
-import { mdxSerialize } from '~/lib/mdx/mdxSerialize'
-// Define minimal block structure for compatibility
-type CMSBlock = {
- blockType: string
- [key: string]: any
-}
-
-export interface ProcessedCMSContent {
- content: MDXRemoteSerializeResult
- blocks: CMSBlock[]
- toc: { content: string; json: any[] }
- plainMarkdown: string
-}
-
-/**
- * Process PayloadCMS rich text content for use in the www blog
- * This function handles both basic content and custom blocks
- */
-export async function processCMSContent(
- richTextContent: any,
- tocDepth: number = 3
-): Promise<ProcessedCMSContent> {
- try {
- // Convert rich text to markdown with blocks converted to existing www syntax
- const { markdown, blocks } = convertRichTextToMarkdownWithBlocks(richTextContent)
-
- // Generate TOC from the converted markdown
- const toc = await generateTocFromMarkdown(markdown, tocDepth)
-
- // Serialize the markdown for MDX (blocks are now converted to existing components)
- const mdxContent = await mdxSerialize(markdown, { tocDepth })
-
- return {
- content: mdxContent,
- blocks,
- toc,
- plainMarkdown: markdown,
- }
- } catch (error) {
- console.error('Error processing CMS content:', error)
-
- // Fallback to basic conversion
- const plainMarkdown = convertRichTextToMarkdown(richTextContent)
- const toc = await generateTocFromMarkdown(plainMarkdown, tocDepth)
- const mdxContent = await mdxSerialize(plainMarkdown, { tocDepth })
-
- return {
- content: mdxContent,
- blocks: [],
- toc,
- plainMarkdown,
- }
- }
-}
-
-/**
- * Legacy function for processing content without blocks (for backward compatibility)
- */
-export async function processCMSContentLegacy(
- richTextContent: any,
- tocDepth: number = 3
-): Promise<{
- content: MDXRemoteSerializeResult
- toc: { content: string; json: any[] }
- plainMarkdown: string
-}> {
- const plainMarkdown = convertRichTextToMarkdown(richTextContent)
- const toc = await generateTocFromMarkdown(plainMarkdown, tocDepth)
- const mdxContent = await mdxSerialize(plainMarkdown, { tocDepth })
-
- return {
- content: mdxContent,
- toc,
- plainMarkdown,
- }
-}
diff --git a/apps/www/lib/constants.ts b/apps/www/lib/constants.ts
index 61a17e59bbb..c1744f0fdad 100644
--- a/apps/www/lib/constants.ts
+++ b/apps/www/lib/constants.ts
@@ -32,15 +32,6 @@ export const SITE_ORIGIN =
? `https://${process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL}`
: 'http://localhost:3000'
-export const CMS_SITE_ORIGIN =
- process.env.NEXT_PUBLIC_VERCEL_ENV === 'production'
- ? // In production, use the actual CMS domain
- process.env.CMS_SITE_ORIGIN || 'https://cms.supabase.com'
- : process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL &&
- typeof process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL === 'string'
- ? `https://${process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL.replace('zone-www-dot-com-git-', 'cms-git-')}`
- : 'http://localhost:3030'
-
export const LW_URL = `${SITE_ORIGIN}/launch-week`
export const LW12_DATE = 'August 12-16 / 7am PT'
diff --git a/apps/www/lib/get-cms-posts.tsx b/apps/www/lib/get-cms-posts.tsx
deleted file mode 100644
index 3cf31b7c465..00000000000
--- a/apps/www/lib/get-cms-posts.tsx
+++ /dev/null
@@ -1,596 +0,0 @@
-import { convertRichTextToMarkdown } from './cms/convertRichTextToMarkdown'
-import { CMS_SITE_ORIGIN } from './constants'
-import { generateReadingTime } from './helpers'
-import { generateTocFromMarkdown } from './toc'
-
-// Payload API configuration
-const PAYLOAD_URL = CMS_SITE_ORIGIN || 'http://localhost:3030'
-const CMS_API_KEY = process.env.CMS_API_KEY
-
-type CMSBlogPost = {
- id: string
- title: string
- slug: string
- description: string
- content: {
- root: {
- children: Array<{
- type: string
- children: Array<{
- text: string
- type: string
- [key: string]: any
- }>
- [key: string]: any
- }>
- }
- }
- date?: string
- launchweek?: string
- toc_depth?: number
- readingTime?: number
- categories?: string[]
- tags?: string[]
- industry?: string[]
- supabase_products?: string[]
- company_size?: string
- region?: string
- logo?: string
- logo_inverse?: string
- imgThumb?: {
- url: string
- }
- createdAt: string
- updatedAt: string
- authors?: {
- author: string
- author_id: string
- position: string
- author_url: string
- author_image_url: {
- url: string
- }
- username: string
- }[]
- meta?: {
- title?: string | null
- imgSocial?: (number | string | null) | Media
- description?: string | null
- }
-}
-
-/**
- * This interface was referenced by `Config`'s JSON-Schema
- * via the `definition` "media".
- */
-export interface Media {
- id: number
- alt?: string | null
- caption?: {
- root: {
- type: string
- children: {
- type: string
- version: number
- [k: string]: unknown
- }[]
- direction: ('ltr' | 'rtl') | null
- format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | ''
- indent: number
- version: number
- }
- [k: string]: unknown
- } | null
- prefix?: string | null
- updatedAt: string
- createdAt: string
- url?: string | null
- thumbnailURL?: string | null
- filename?: string | null
- mimeType?: string | null
- filesize?: number | null
- width?: number | null
- height?: number | null
- focalX?: number | null
- focalY?: number | null
- sizes?: {
- thumbnail?: {
- url?: string | null
- width?: number | null
- height?: number | null
- mimeType?: string | null
- filesize?: number | null
- filename?: string | null
- }
- square?: {
- url?: string | null
- width?: number | null
- height?: number | null
- mimeType?: string | null
- filesize?: number | null
- filename?: string | null
- }
- small?: {
- url?: string | null
- width?: number | null
- height?: number | null
- mimeType?: string | null
- filesize?: number | null
- filename?: string | null
- }
- medium?: {
- url?: string | null
- width?: number | null
- height?: number | null
- mimeType?: string | null
- filesize?: number | null
- filename?: string | null
- }
- large?: {
- url?: string | null
- width?: number | null
- height?: number | null
- mimeType?: string | null
- filesize?: number | null
- filename?: string | null
- }
- xlarge?: {
- url?: string | null
- width?: number | null
- height?: number | null
- mimeType?: string | null
- filesize?: number | null
- filename?: string | null
- }
- og?: {
- url?: string | null
- width?: number | null
- height?: number | null
- mimeType?: string | null
- filesize?: number | null
- filename?: string | null
- }
- }
-}
-
-type ProcessedPost = {
- slug: string
- title: string
- description: string
- date: string
- formattedDate: string
- readingTime: string
- industry?: string[]
- supabase_products?: string[]
- company_size?: string
- region?: string
- logo?: string
- logo_inverse?: string
- authors: Array<{
- author: string
- author_id: string
- position: string
- author_url: string
- author_image_url: string | null
- username: string
- }>
- toc_depth: number
- imgThumb: string | null
- url: string
- path: string
- isCMS: boolean
- tags: string[]
- content: string
- meta?: {
- title?: string | null
- imgSocial?: (number | string | null) | Media
- description?: string | null
- }
-}
-
-/**
- * Fetch all blog post slugs from the CMS
- */
-export async function getAllCMSPostSlugs() {
- try {
- const response = await fetch(
- `${PAYLOAD_URL}/api/posts?limit=100&depth=1&draft=false&where[_status][equals]=published`,
- {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- }
- )
-
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`)
- }
-
- const contentType = response.headers.get('content-type') || ''
- if (!contentType.toLowerCase().includes('application/json')) {
- const body = await response.text()
- console.warn(
- `[getAllCMSPostSlugs] Non-JSON response from ${PAYLOAD_URL}/api/posts (content-type: '${contentType}'). Returning empty slugs. Body (truncated): ${body.slice(
- 0,
- 200
- )}`
- )
- return []
- }
- const data = await response.json()
- // console.log(
- // '[getAllCMSPostSlugs] Found posts:',
- // data.docs.map((post: any) => ({
- // id: post.id,
- // title: post.title,
- // slug: post.slug,
- // status: post._status,
- // }))
- // )
-
- return data.docs
- .filter((post: CMSBlogPost) => post.slug) // Filter out posts with null/undefined slugs
- .map((post: CMSBlogPost) => ({
- params: {
- slug: post.slug,
- },
- }))
- } catch (_error) {
- // don't console error to avoid noise if env vars not set
- return []
- }
-}
-
-/**
- * Fetch a single blog post from the CMS by slug
- */
-export async function getCMSPostBySlug(slug: string, preview = false) {
- // console.log(
- // `[getCMSPostBySlug] Fetching post '${slug}', preview: ${preview}, from ${PAYLOAD_URL}`
- // )
-
- try {
- let url: string
- let response: Response
-
- if (!preview) {
- // For published posts, try to get the latest published version using versions API
- const versionsUrl = `${PAYLOAD_URL}/api/posts/versions?where[version.slug][equals]=${slug}&where[version._status][equals]=published&sort=-updatedAt&limit=1&depth=2`
-
- response = await fetch(versionsUrl, {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- // For published posts: allow static generation with revalidation
- next: { revalidate: 60 }, // 1 minute
- })
-
- if (response.ok) {
- const versionsData = await response.json()
- if (versionsData.docs && versionsData.docs.length > 0) {
- const latestPublishedVersion = versionsData.docs[0].version
- if (latestPublishedVersion) {
- return processPostData(latestPublishedVersion)
- }
- }
- }
- }
-
- // Fallback to regular API (for preview mode or if versions API fails)
- if (preview) {
- // In preview mode, always try to get the latest draft first
- url = `${PAYLOAD_URL}/api/posts?where[slug][equals]=${slug}&depth=2&draft=true`
-
- response = await fetch(url, {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- // cache: 'no-store',
- next: { revalidate: 0 },
- })
-
- // If no draft found, try published version
- if (!response.ok || (await response.clone().json()).docs?.length === 0) {
- url = `${PAYLOAD_URL}/api/posts?where[slug][equals]=${slug}&depth=2&draft=false`
- response = await fetch(url, {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- // cache: 'no-store',
- next: { revalidate: 0 },
- })
- }
- } else {
- // For non-preview mode, get published version
- url = `${PAYLOAD_URL}/api/posts?where[slug][equals]=${slug}&depth=2&draft=false`
-
- response = await fetch(url, {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- // For published posts: allow static generation with revalidation
- next: { revalidate: 60 }, // 1 minute
- })
- }
-
- if (!response.ok) {
- console.error(`[getCMSPostBySlug] HTTP error: ${response.status} ${response.statusText}`)
- const errorText = await response.text()
- console.error(`[getCMSPostBySlug] Error response body:`, errorText)
- throw new Error(`HTTP error! status: ${response.status}`)
- }
-
- const contentType = response.headers.get('content-type') || ''
- if (!contentType.toLowerCase().includes('application/json')) {
- const body = await response.text()
- console.warn(
- `[getCMSPostBySlug] Non-JSON response from ${url} (content-type: '${contentType}'). Returning null. Body (truncated): ${body.slice(
- 0,
- 200
- )}`
- )
- return null
- }
- const data = await response.json()
-
- if (!data.docs.length && !preview) {
- return null
- }
-
- // If we're in preview mode and there's no draft, try to get the published version
- if (!data.docs.length && preview) {
- const publishedUrl = `${PAYLOAD_URL}/api/posts?where[slug][equals]=${slug}&depth=2`
-
- const publishedResponse = await fetch(publishedUrl, {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- })
-
- if (!publishedResponse.ok) {
- console.error(
- `[getCMSPostBySlug] HTTP error for published version: ${publishedResponse.status}`
- )
- throw new Error(`HTTP error! status: ${publishedResponse.status}`)
- }
-
- const publishedContentType = publishedResponse.headers.get('content-type') || ''
- if (!publishedContentType.toLowerCase().includes('application/json')) {
- const body = await publishedResponse.text()
- console.warn(
- `[getCMSPostBySlug] Non-JSON response from ${publishedUrl} (content-type: '${publishedContentType}'). Returning null. Body (truncated): ${body.slice(
- 0,
- 200
- )}`
- )
- return null
- }
- const publishedData = await publishedResponse.json()
-
- if (!publishedData.docs.length) {
- return null
- }
-
- return processPostData(publishedData.docs[0])
- }
-
- // If we have a post (either draft or published), process it
- const post = data.docs[0]
-
- try {
- const processedPost = await processPostData(post)
-
- return processedPost
- } catch (error) {
- console.error(`[getCMSPostBySlug] Error in processPostData:`, error)
- return null
- }
- } catch (error) {
- console.error('Error fetching CMS post by slug:', error)
- return null
- }
-}
-
-// Helper function to process post data
-async function processPostData(post: any) {
- try {
- const options: Intl.DateTimeFormatOptions = { month: 'long', day: 'numeric', year: 'numeric' }
- const formattedDate = new Date(post.date || new Date()).toLocaleDateString('en-IN', options)
-
- const markdownContent = convertRichTextToMarkdown(post.content)
-
- const readingTime = post.readingTime || generateReadingTime(markdownContent)
-
- // Generate TOC from content for CMS blog posts
- const tocResult = await generateTocFromMarkdown(
- markdownContent,
- post.toc_depth ? post.toc_depth : 3
- )
-
- // Extract imgThumb and imgSocial URLs from the nested structure
- const imgThumbUrl = post.imgThumb?.url
- ? typeof post.imgThumb.url === 'string' && post.imgThumb.url.includes('http')
- ? post.imgThumb.url
- : `${PAYLOAD_URL}${post.imgThumb.url}`
- : null
- const imgSocialUrl = post.meta?.imgSocial
- ? typeof post.meta?.imgSocial === 'string' && post.meta?.imgSocial.includes('http')
- ? post.meta?.imgSocial
- : `${PAYLOAD_URL}${post.meta?.imgSocial}`
- : imgThumbUrl
-
- const processedData = {
- slug: post.slug,
- source: markdownContent,
- title: post.title || 'Untitled Post',
- date: post.date || new Date().toISOString(),
- formattedDate,
- readingTime,
- launchweek: post.launchweek || null,
- authors:
- post.authors?.map((author: any) => ({
- author: author.author || 'Unknown Author',
- author_id: author.author_id || '',
- position: author.position || '',
- author_url: author.author_url || '#',
- author_image_url: author.author_image_url?.url
- ? typeof author.author_image_url.url === 'string' &&
- author.author_image_url.url.includes('http')
- ? author.author_image_url?.url
- : `${PAYLOAD_URL}${author.author_image_url.url}`
- : null,
- username: author.username || '',
- })) || [],
- toc_depth: post.toc_depth || 3,
- imgThumb: imgThumbUrl,
- imgSocial: imgSocialUrl,
- url: `/blog/${post.slug}`,
- path: `/blog/${post.slug}`,
- isCMS: true,
- content: markdownContent,
- richContent: post.content,
- categories: post.categories?.map((category: any) => category.name) || [],
- tags: post.tags || [],
- toc: {
- content: tocResult.content,
- json: tocResult.json,
- },
- }
-
- return processedData
- } catch (error) {
- console.error(`[processPostData] Error processing post data:`, error)
- throw error
- }
-}
-
-/**
- * Fetch all blog posts from the CMS
- */
-export async function getAllCMSPosts({
- limit,
- tags,
- currentPostSlug,
-}: {
- limit?: number
- tags?: string[]
- currentPostSlug?: string
-} = {}): Promise<ProcessedPost[]> {
- try {
- const response = await fetch(
- `${PAYLOAD_URL}/api/posts?depth=2&draft=false&where[_status][equals]=published`,
- {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- // cache: 'no-store', // Ensure we always get fresh data
- next: { revalidate: 30 }, // Disable caching for this fetch
- }
- )
-
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`)
- }
-
- const contentType = response.headers.get('content-type') || ''
- if (!contentType.toLowerCase().includes('application/json')) {
- const body = await response.text()
- console.warn(
- `[getAllCMSPosts] Non-JSON response from ${PAYLOAD_URL}/api/posts (content-type: '${contentType}'). Returning empty posts. Body (truncated): ${body.slice(
- 0,
- 200
- )}`
- )
- return []
- }
- const data = await response.json()
-
- let posts = data.docs
- .filter((post: CMSBlogPost) => post.slug !== currentPostSlug)
- .map((post: CMSBlogPost) => {
- const options: Intl.DateTimeFormatOptions = {
- month: 'long',
- day: 'numeric',
- year: 'numeric',
- }
- const formattedDate = new Date(post.date || new Date()).toLocaleDateString('en-IN', options)
- const markdownContent = convertRichTextToMarkdown(post.content)
- const readingTime = post.readingTime || generateReadingTime(markdownContent)
-
- // Extract imgThumb and imgSocial URLs from the nested structure (handle absolute and relative)
- const imgThumbUrl = post.imgThumb?.url
- ? typeof post.imgThumb.url === 'string' && post.imgThumb.url.includes('http')
- ? post.imgThumb.url
- : `${PAYLOAD_URL}${post.imgThumb.url}`
- : null
- const imgSocialUrl = post.meta?.imgSocial
- ? typeof post.meta?.imgSocial === 'string' && post.meta?.imgSocial.includes('http')
- ? post.meta?.imgSocial
- : `${PAYLOAD_URL}${post.meta?.imgSocial}`
- : imgThumbUrl
-
- return {
- slug: post.slug || '',
- title: post.title || '',
- description: post.description || '',
- date: post.date || new Date().toISOString(),
- formattedDate,
- readingTime,
- authors:
- post.authors?.map((author: any) => ({
- author: author.author || '',
- author_id: author.author_id || '',
- position: author.position || '',
- author_url: author.author_url || '#',
- author_image_url: author.author_image_url?.url
- ? typeof author.author_image_url.url === 'string' &&
- author.author_image_url.url.includes('http')
- ? author.author_image_url.url
- : `${PAYLOAD_URL}${author.author_image_url.url}`
- : null,
- username: author.username || '',
- })) || [],
- toc_depth: post.toc_depth || 3,
- imgThumb: imgThumbUrl,
- imgSocial: imgSocialUrl,
- url: `/blog/${post.slug || ''}`,
- path: `/blog/${post.slug || ''}`,
- isCMS: true,
- categories: post.categories?.map((category: any) => category.name) || [],
- tags: post.tags || [],
- content: markdownContent,
- }
- })
-
- // Sort by date (newest first)
- posts = posts.sort(
- (a: ProcessedPost, b: ProcessedPost) =>
- new Date(b.date).getTime() - new Date(a.date).getTime()
- )
-
- // Filter by tags if provided
- if (tags && tags.length > 0) {
- posts = posts.filter((post: ProcessedPost) => {
- const found = tags.some((tag) => post.tags?.includes(tag))
- return found
- })
- }
-
- // Limit results if specified
- if (limit) {
- posts = posts.slice(0, limit)
- }
-
- return posts
- } catch (_error) {
- // don't console error to avoid noise if env vars not set
- return []
- }
-}
diff --git a/apps/www/lib/remotePatterns.js b/apps/www/lib/remotePatterns.js
index 02ff77d2b83..ce504c21b7f 100644
--- a/apps/www/lib/remotePatterns.js
+++ b/apps/www/lib/remotePatterns.js
@@ -1,43 +1,3 @@
-const CMS_SITE_ORIGIN =
- process.env.NEXT_PUBLIC_VERCEL_ENV === 'production'
- ? 'https://cms.supabase.com'
- : process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL &&
- typeof process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL === 'string'
- ? `https://${process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL?.replace('zone-www-dot-com-git-', 'cms-git-')}`
- : 'http://localhost:3030'
-
-// Function to generate CMS remote patterns from CMS_SITE_ORIGIN
-function generateCMSRemotePatterns() {
- const patterns = []
-
- try {
- const cmsUrl = new URL(CMS_SITE_ORIGIN)
- const cmsHostname = cmsUrl.hostname
- const cmsProtocol = cmsUrl.protocol?.replace(':', '')
-
- // Validate hostname
- if (!cmsHostname) {
- console.warn('[remotePatterns] Invalid hostname extracted from CMS_SITE_ORIGIN')
- return patterns
- }
-
- // Add patterns for the current CMS hostname
- const pathPatterns = ['/media/**', '/api/media/**', '/api/media/file/**']
-
- pathPatterns.forEach((pathname) => {
- patterns.push({
- protocol: cmsProtocol,
- hostname: cmsHostname,
- pathname,
- })
- })
- } catch (error) {
- console.warn(`[remotePatterns] Failed to parse CMS_SITE_ORIGIN: "${CMS_SITE_ORIGIN}"`, error)
- }
-
- return patterns
-}
-
module.exports = [
{
protocol: 'https',
@@ -147,12 +107,6 @@ module.exports = [
port: '',
pathname: '/dms/image/**',
},
- {
- protocol: 'https',
- hostname: 'cms.supabase.com',
- port: '',
- pathname: '**',
- },
// OG Edge Function
{
protocol: 'https',
@@ -160,6 +114,4 @@ module.exports = [
port: '',
pathname: '/functions/v1/generate-og',
},
- // Dynamically generated CMS patterns based on CMS_SITE_ORIGIN
- ...generateCMSRemotePatterns(),
]
diff --git a/apps/www/next.config.mjs b/apps/www/next.config.mjs
index 67903e5e1cf..6f92ead8e81 100644
--- a/apps/www/next.config.mjs
+++ b/apps/www/next.config.mjs
@@ -1,7 +1,8 @@
+import { remarkCodeHike } from '@code-hike/mdx'
import bundleAnalyzer from '@next/bundle-analyzer'
import nextMdx from '@next/mdx'
import { withSentryConfig } from '@sentry/nextjs'
-
+import codeHikeTheme from 'config/code-hike.theme.json' with { type: 'json' }
import rehypeSlug from 'rehype-slug'
import remarkGfm from 'remark-gfm'
@@ -9,9 +10,6 @@ import redirects from './lib/redirects.js'
import remotePatterns from './lib/remotePatterns.js'
import rewrites from './lib/rewrites.js'
-import { remarkCodeHike } from '@code-hike/mdx'
-import codeHikeTheme from 'config/code-hike.theme.json' with { type: 'json' }
-
const withMDX = nextMdx({
extension: /\.mdx?$/,
options: {
@@ -90,16 +88,6 @@ const nextConfig = {
// No X-Frame-Options header to allow iframe embedding
],
},
- {
- source: '/api-v2/cms/preview',
- headers: [
- {
- key: 'content-type',
- value: 'text/html',
- },
- // No X-Frame-Options header to allow iframe embedding
- ],
- },
// Default X-Frame-Options for all other paths
{
source: '/((?!blog|api-v2/cms/preview).*)',
diff --git a/apps/www/package.json b/apps/www/package.json
index 15905a8a84b..d9488aff7a4 100644
--- a/apps/www/package.json
+++ b/apps/www/package.json
@@ -30,7 +30,6 @@
"@octokit/graphql": "^8.0.0",
"@octokit/plugin-paginate-graphql": "^4.0.0",
"@octokit/rest": "^21.0.0",
- "@payloadcms/live-preview-react": "^3.0.0",
"@radix-ui/react-dialog": "^1.0.5",
"@sentry/nextjs": "catalog:",
"@supabase/supabase-js": "catalog:",
@@ -91,7 +90,7 @@
"yup": "^1.4.0"
},
"devDependencies": {
- "@babel/core": "^7.28.4",
+ "@babel/core": "*",
"@hookform/resolvers": "^3.1.1",
"@types/animejs": "^3.1.12",
"@types/classnames": "^2.3.1",
diff --git a/apps/www/scripts/generateStaticContent.mjs b/apps/www/scripts/generateStaticContent.mjs
index 38a82344677..ad6dcc55614 100644
--- a/apps/www/scripts/generateStaticContent.mjs
+++ b/apps/www/scripts/generateStaticContent.mjs
@@ -1,24 +1,18 @@
+// @ts-check
+
+import fsSync, { promises as fs } from 'fs'
+import path from 'path'
+import { fileURLToPath } from 'url'
import dayjs from 'dayjs'
import advancedFormat from 'dayjs/plugin/advancedFormat.js'
import utc from 'dayjs/plugin/utc.js'
-import fsSync, { promises as fs } from 'fs'
import matter from 'gray-matter'
-import path from 'path'
-import { fileURLToPath } from 'url'
dayjs.extend(utc)
dayjs.extend(advancedFormat)
// Constants
const FILENAME_SUBSTRING = 11 // based on YYYY-MM-DD format
-const CMS_SITE_ORIGIN =
- process.env.NEXT_PUBLIC_VERCEL_ENV === 'production'
- ? 'https://cms.supabase.com'
- : process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL &&
- typeof process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL === 'string'
- ? `https://${process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL?.replace('zone-www-dot-com-git-', 'cms-git-')}`
- : 'http://localhost:3030'
-const CMS_API_KEY = process.env.CMS_API_KEY
/**
* Fixes Safari dates sorting bug
@@ -82,72 +76,14 @@ const getStaticBlogPosts = () => {
}
}
-/**
- * Get CMS blog posts
- */
-const getCMSBlogPosts = async () => {
- try {
- const url = `${CMS_SITE_ORIGIN}/api/posts?depth=2&draft=false&where[_status][equals]=published`
-
- const response = await fetch(url, {
- headers: {
- 'Content-Type': 'application/json',
- ...(CMS_API_KEY && { Authorization: `Bearer ${CMS_API_KEY}` }),
- },
- })
-
- if (!response.ok) {
- const responseText = await response.text()
-
- throw new Error(`HTTP error! status: ${response.status}`)
- }
-
- const contentType = response.headers.get('content-type') || ''
- if (!contentType.toLowerCase().includes('application/json')) {
- const body = await response.text()
- console.warn(
- `[getCMSBlogPosts] Non-JSON response from ${CMS_SITE_ORIGIN}/api/posts (content-type: '${contentType}'). Returning empty posts. Body (truncated): ${body.slice(0, 200)}`
- )
- return []
- }
-
- const data = await response.json()
-
- const posts = data.docs
- .filter((post) => post.slug && post.title && post.description)
- .map((post) => {
- const options = { month: 'long', day: 'numeric', year: 'numeric' }
- const formattedDate = new Date(post.date || new Date()).toLocaleDateString('en-IN', options)
-
- return {
- slug: post.slug,
- title: post.title,
- description: post.description,
- date: post.date || null, // Keep null if no date instead of using current time
- formattedDate,
- url: `/blog/${post.slug}`,
- isCMS: true,
- ...post,
- }
- })
-
- return posts
- } catch (_error) {
- // don't console error to avoid noise if env vars not set
- return []
- }
-}
-
/**
* Get all blog posts from both sources
*/
const getAllBlogPosts = async () => {
const staticPosts = getStaticBlogPosts()
- const cmsPosts = await getCMSBlogPosts()
-
// Combine and sort all posts by date
- const allPosts = [...staticPosts, ...cmsPosts]
+ const allPosts = [...staticPosts]
// Filter out posts without valid dates and sort
const validPosts = allPosts.sort((a, b) => sortDates(a, b, 'desc'))
@@ -291,12 +227,13 @@ try {
`
}
- const formattedDate = allBlogPosts.length > 0
- ? dayjs(allBlogPosts[0].date)
- .utcOffset(0, true)
- .startOf('day')
- .format('ddd, DD MMM YYYY HH:mm:ss [-0700]')
- : dayjs().utcOffset(0, true).startOf('day').format('ddd, DD MMM YYYY HH:mm:ss [-0700]')
+ const formattedDate =
+ allBlogPosts.length > 0
+ ? dayjs(allBlogPosts[0].date)
+ .utcOffset(0, true)
+ .startOf('day')
+ .format('ddd, DD MMM YYYY HH:mm:ss [-0700]')
+ : dayjs().utcOffset(0, true).startOf('day').format('ddd, DD MMM YYYY HH:mm:ss [-0700]')
const rss = `
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
diff --git a/apps/www/types/post.ts b/apps/www/types/post.ts
index 30633e4fc78..e439e0fb908 100644
--- a/apps/www/types/post.ts
+++ b/apps/www/types/post.ts
@@ -1,6 +1,7 @@
-import type { getSortedPosts } from 'lib/posts'
import type { MDXRemoteSerializeResult } from 'next-mdx-remote'
+import type { getSortedPosts } from '@/lib/posts'
+
export interface PostTypes {
type: 'casestudy' | 'blog' | 'event'
slug?: string
@@ -40,8 +41,7 @@ export interface PostTypes {
href: string
target?: '_blank' | '_self'
label?: string
- } // used on event previews to link to a custom event page
- isCMS?: boolean
+ }
}
export type Event = {
@@ -74,18 +74,6 @@ export type StaticAuthor = {
position: string
}
-export type CMSAuthor = {
- author: string
- author_image_url:
- | {
- url: string
- }
- | string
- | null
- author_url: string
- position: string
-}
-
export type Blog = {
slug: string
title: string
@@ -93,7 +81,7 @@ export type Blog = {
content: MDXRemoteSerializeResult
toc: string | { content: string }
author?: string
- authors?: (CMSAuthor | StaticAuthor)[]
+ authors?: StaticAuthor[]
date: string
categories?: string[]
tags?:
@@ -119,7 +107,6 @@ export type Blog = {
meta_title?: string
meta_description?: string
meta_image?: string
- isCMS?: boolean
}
export type BlogData = {
@@ -129,7 +116,7 @@ export type BlogData = {
content: MDXRemoteSerializeResult
toc: string | { content: string }
author?: string
- authors?: (CMSAuthor | StaticAuthor)[]
+ authors?: StaticAuthor[]
date: string
categories?: string[]
tags?:
@@ -155,7 +142,6 @@ export type BlogData = {
meta_description?: string
meta_image?: string
video?: string
- isCMS?: boolean
}
export type Tag =
@@ -206,21 +192,6 @@ export interface EventData {
meta_title?: string
meta_description?: string
video?: string
- isCMS?: boolean
-}
-
-export interface CMSPostTypes extends PostTypes {
- isCMS?: boolean
- authors?: Array<{
- author: string
- author_id: string
- position: string
- author_url: string
- author_image_url: {
- url: string
- }
- username: string
- }>
}
export type PostReturnType = ReturnType<typeof getSortedPosts>[number]
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 47f14406581..7251422ba4a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1711,9 +1711,6 @@ importers:
'@octokit/rest':
specifier: ^21.0.0
version: 21.1.1
- '@payloadcms/live-preview-react':
- specifier: ^3.0.0
'@radix-ui/react-dialog':
specifier: ^1.0.5
@@ -1890,7 +1887,7 @@ importers:
version: 1.4.0
devDependencies:
'@babel/core':
- specifier: ^7.28.4
+ specifier: '*'
version: 7.29.0([email protected])
'@hookform/resolvers':
specifier: ^3.1.1
@@ -22485,7 +22482,7 @@ snapshots:
'@tanstack/react-virtual': 3.13.12([email protected]([email protected]))([email protected])
react: 18.3.1
react-dom: 18.3.1([email protected])
- use-sync-external-store: 1.5.0([email protected])
+ use-sync-external-store: 1.6.0([email protected])
dependencies:
@@ -35581,7 +35578,7 @@ snapshots:
dependencies:
mobx: 6.11.0
react: 18.3.1
- use-sync-external-store: 1.5.0([email protected])
+ use-sync-external-store: 1.6.0([email protected])
optionalDependencies:
react-dom: 18.3.1([email protected])