Skip to content

Commit 131095b

Browse files
committed
test cache components
1 parent 55b9c3b commit 131095b

File tree

19 files changed

+13229
-19362
lines changed

19 files changed

+13229
-19362
lines changed

app/(personal)/[slug]/page.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {Metadata, ResolvingMetadata} from 'next'
66
import {toPlainText, type PortableTextBlock} from 'next-sanity'
77
import {draftMode} from 'next/headers'
88
import {notFound} from 'next/navigation'
9+
import {resolveCookiePerspective} from 'next-sanity/live/use-cache'
910

1011
type Props = {
1112
params: Promise<{slug: string}>
@@ -15,10 +16,12 @@ export async function generateMetadata(
1516
{params}: Props,
1617
parent: ResolvingMetadata,
1718
): Promise<Metadata> {
19+
const perspective = await resolveCookiePerspective()
1820
const {data: page} = await sanityFetch({
1921
query: pagesBySlugQuery,
2022
params,
2123
stega: false,
24+
perspective,
2225
})
2326

2427
return {
@@ -38,7 +41,8 @@ export async function generateStaticParams() {
3841
}
3942

4043
export default async function PageSlugRoute({params}: Props) {
41-
const {data} = await sanityFetch({query: pagesBySlugQuery, params})
44+
const perspective = await resolveCookiePerspective()
45+
const {data} = await sanityFetch({query: pagesBySlugQuery, params, perspective})
4246

4347
// Only show the 404 page if we're in production, when in draft mode we might be about to create a page on this slug, and live reload won't work on the 404 route
4448
if (!data?._id && !(await draftMode()).isEnabled) {

app/(personal)/client-functions.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
'use client'
22

3+
import {type SyncTag} from '@sanity/client'
34
import {isCorsOriginError} from 'next-sanity/live'
45
import {toast} from 'sonner'
56

@@ -27,3 +28,16 @@ export function handleError(error: unknown) {
2728
})
2829
}
2930
}
31+
32+
export async function revalidateSyncTags(tags: SyncTag[]): Promise<'refresh'> {
33+
const url = new URL('/api/revalidate-sync-tags', window.location.origin)
34+
for (const tag of tags) {
35+
url.searchParams.append('tag', tag)
36+
}
37+
const response = await fetch(url, {method: 'POST'})
38+
if (!response.ok) {
39+
throw new Error('Failed to revalidate sync tags')
40+
}
41+
console.log('revalidating sync tags', tags)
42+
return 'refresh'
43+
}

app/(personal)/layout.tsx

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,16 @@ import {VisualEditing} from 'next-sanity/visual-editing'
1111
import {draftMode} from 'next/headers'
1212
import {Suspense} from 'react'
1313
import {Toaster} from 'sonner'
14-
import {handleError} from './client-functions'
14+
import {handleError, revalidateSyncTags} from './client-functions'
1515
import {DraftModeToast} from './DraftModeToast'
1616
import {SpeedInsights} from '@vercel/speed-insights/next'
17+
import {resolveCookiePerspective} from 'next-sanity/live/use-cache'
1718

1819
export async function generateMetadata(): Promise<Metadata> {
20+
const perspective = await resolveCookiePerspective()
1921
const [{data: settings}, {data: homePage}] = await Promise.all([
20-
sanityFetch({query: settingsQuery, stega: false}),
21-
sanityFetch({query: homePageQuery, stega: false}),
22+
sanityFetch({query: settingsQuery, stega: false, perspective}),
23+
sanityFetch({query: homePageQuery, stega: false, perspective}),
2224
])
2325

2426
const ogImage = urlForOpenGraphImage(
@@ -43,8 +45,9 @@ export const viewport: Viewport = {
4345
themeColor: '#000',
4446
}
4547

46-
export default async function IndexRoute({children}: {children: React.ReactNode}) {
47-
const {data} = await sanityFetch({query: settingsQuery})
48+
export default async function PersonalLayout({children}: {children: React.ReactNode}) {
49+
const perspective = await resolveCookiePerspective()
50+
const {data} = await sanityFetch({query: settingsQuery, perspective})
4851
return (
4952
<>
5053
<div className="flex min-h-screen flex-col bg-white text-black">
@@ -66,7 +69,7 @@ export default async function IndexRoute({children}: {children: React.ReactNode}
6669
</Suspense>
6770
</div>
6871
<Toaster />
69-
<SanityLive onError={handleError} />
72+
<SanityLive onError={handleError} revalidateSyncTags={revalidateSyncTags} />
7073
{(await draftMode()).isEnabled && (
7174
<>
7275
<DraftModeToast />

app/(personal)/page.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import {studioUrl} from '@/sanity/lib/api'
33
import {sanityFetch} from '@/sanity/lib/live'
44
import {homePageQuery} from '@/sanity/lib/queries'
55
import Link from 'next/link'
6+
import {resolveCookiePerspective} from 'next-sanity/live/use-cache'
67

78
export default async function IndexRoute() {
8-
const {data} = await sanityFetch({query: homePageQuery})
9+
const perspective = await resolveCookiePerspective()
10+
const {data} = await sanityFetch({query: homePageQuery, perspective})
911

1012
if (!data) {
1113
return (

app/(personal)/projects/[slug]/page.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {createDataAttribute, toPlainText} from 'next-sanity'
1010
import {draftMode} from 'next/headers'
1111
import Link from 'next/link'
1212
import {notFound} from 'next/navigation'
13+
import {resolveCookiePerspective} from 'next-sanity/live/use-cache'
1314

1415
type Props = {
1516
params: Promise<{slug: string}>
@@ -19,9 +20,11 @@ export async function generateMetadata(
1920
{params}: Props,
2021
parent: ResolvingMetadata,
2122
): Promise<Metadata> {
23+
const perspective = await resolveCookiePerspective()
2224
const {data: project} = await sanityFetch({
2325
query: projectBySlugQuery,
2426
params,
27+
perspective,
2528
stega: false,
2629
})
2730
const ogImage = urlForOpenGraphImage(
@@ -51,7 +54,8 @@ export async function generateStaticParams() {
5154
}
5255

5356
export default async function ProjectSlugRoute({params}: Props) {
54-
const {data} = await sanityFetch({query: projectBySlugQuery, params})
57+
const perspective = await resolveCookiePerspective()
58+
const {data} = await sanityFetch({query: projectBySlugQuery, params, perspective})
5559

5660
// Only show the 404 page if we're in production, when in draft mode we might be about to create a project on this slug, and live reload won't work on the 404 route
5761
if (!data?._id && !(await draftMode()).isEnabled) {
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import type {NextRequest} from 'next/server'
2+
import {unstable_expireTag as expireTag} from 'next/cache'
3+
import {draftMode} from 'next/headers'
4+
5+
export async function POST(request: NextRequest) {
6+
const {isEnabled: isDraftModeEnabled} = await draftMode()
7+
const tags = request.nextUrl.searchParams
8+
.getAll('tag')
9+
.map((tag) => (isDraftModeEnabled ? `drafts:${tag}` : `sanity:${tag}`))
10+
11+
// If in draft mode all tags must be prefixed with 'draft:'
12+
// if ((await draftMode()).isEnabled) {
13+
// if (!tags.every((tag) => tag.startsWith('drafts:'))) {
14+
// return Response.json(
15+
// {error: 'All tags must be prefixed with "drafts:" in draft mode'},
16+
// {status: 400},
17+
// )
18+
// }
19+
// } else if (!tags.every((tag) => tag.startsWith('sanity:'))) {
20+
// return Response.json(
21+
// {error: 'All tags must be prefixed with "sanity:" in production mode'},
22+
// {status: 400},
23+
// )
24+
// }
25+
26+
expireTag(...tags)
27+
console.log(`<SanityLive /> expired tags: ${tags.join(', ')}`)
28+
29+
return Response.json(tags)
30+
}

app/layout.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const mono = IBM_Plex_Mono({
1919
weight: ['500', '700'],
2020
})
2121

22-
export default async function RootLayout({children}: {children: React.ReactNode}) {
22+
export default function RootLayout({children}: {children: React.ReactNode}) {
2323
return (
2424
<html lang="en" className={`${mono.variable} ${sans.variable} ${serif.variable}`}>
2525
<body>{children}</body>

app/studio/[[...index]]/page.tsx

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
'use cache'
2+
13
/**
24
* This route is responsible for the built-in authoring environment using Sanity Studio v3.
35
* All routes under /studio will be handled by this file using Next.js' catch-all routes:
@@ -9,11 +11,16 @@
911

1012
import config from '@/sanity.config'
1113
import {NextStudio} from 'next-sanity/studio'
14+
import {unstable_cacheLife as cacheLife} from 'next/cache'
1215

13-
export const dynamic = 'force-static'
14-
15-
export {metadata, viewport} from 'next-sanity/studio'
16-
17-
export default function StudioPage() {
18-
return <NextStudio config={config} />
16+
export default async function StudioPage() {
17+
cacheLife('max')
18+
return (
19+
<>
20+
<meta name="referrer" content="same-origin" />
21+
<meta name="robots" content="noindex" />
22+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
23+
<NextStudio config={config} />
24+
</>
25+
)
1926
}

next-env.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/// <reference types="next" />
22
/// <reference types="next/image-types/global" />
3-
/// <reference path="./.next/types/routes.d.ts" />
3+
import "./.next/types/routes.d.ts";
44

55
// NOTE: This file should not be edited
66
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

next.config.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1-
import {NextConfig} from 'next'
1+
import type {NextConfig} from 'next'
22

33
const config: NextConfig = {
44
// Helps catch bugs
55
reactStrictMode: true,
66
experimental: {
77
// Speeds up performance by automatically generating useMemo and useCallback in client components
88
reactCompiler: true,
9+
// Optimal Sanity Live experience
10+
cacheComponents: true,
911
},
12+
transpilePackages: ['next-sanity'],
1013
images: {
1114
remotePatterns: [{hostname: 'cdn.sanity.io'}],
1215
},

0 commit comments

Comments
 (0)