Unverified Commit cfd816dd authored by Cody Olsen's avatar Cody Olsen Committed by GitHub

Update Sanity example to next v15 (#71640)

parent ce41f6bc
...@@ -5,7 +5,7 @@ import { draftMode } from "next/headers"; ...@@ -5,7 +5,7 @@ import { draftMode } from "next/headers";
export async function disableDraftMode() { export async function disableDraftMode() {
"use server"; "use server";
await Promise.allSettled([ await Promise.allSettled([
draftMode().disable(), (await draftMode()).disable(),
// Simulate a delay to show the loading state // Simulate a delay to show the loading state
new Promise((resolve) => setTimeout(resolve, 1000)), new Promise((resolve) => setTimeout(resolve, 1000)),
]); ]);
......
...@@ -9,7 +9,6 @@ import { ...@@ -9,7 +9,6 @@ import {
} from "next-sanity"; } from "next-sanity";
import { Inter } from "next/font/google"; import { Inter } from "next/font/google";
import { draftMode } from "next/headers"; import { draftMode } from "next/headers";
import { Suspense } from "react";
import AlertBanner from "./alert-banner"; import AlertBanner from "./alert-banner";
import PortableText from "./portable-text"; import PortableText from "./portable-text";
...@@ -56,11 +55,21 @@ const inter = Inter({ ...@@ -56,11 +55,21 @@ const inter = Inter({
display: "swap", display: "swap",
}); });
async function Footer() { export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const data = await sanityFetch({ query: settingsQuery }); const data = await sanityFetch({ query: settingsQuery });
const footer = data?.footer || []; const footer = data?.footer || [];
const { isEnabled: isDraftMode } = await draftMode();
return ( return (
<html lang="en" className={`${inter.variable} bg-white text-black`}>
<body>
<section className="min-h-screen">
{isDraftMode && <AlertBanner />}
<main>{children}</main>
<footer className="bg-accent-1 border-accent-2 border-t"> <footer className="bg-accent-1 border-accent-2 border-t">
<div className="container mx-auto px-5"> <div className="container mx-auto px-5">
{footer.length > 0 ? ( {footer.length > 0 ? (
...@@ -91,25 +100,8 @@ async function Footer() { ...@@ -91,25 +100,8 @@ async function Footer() {
)} )}
</div> </div>
</footer> </footer>
);
}
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className={`${inter.variable} bg-white text-black`}>
<body>
<section className="min-h-screen">
{draftMode().isEnabled && <AlertBanner />}
<main>{children}</main>
<Suspense>
<Footer />
</Suspense>
</section> </section>
{draftMode().isEnabled && <VisualEditing />} {isDraftMode && <VisualEditing />}
<SpeedInsights /> <SpeedInsights />
</body> </body>
</html> </html>
......
...@@ -17,7 +17,7 @@ import { postQuery, settingsQuery } from "@/sanity/lib/queries"; ...@@ -17,7 +17,7 @@ import { postQuery, settingsQuery } from "@/sanity/lib/queries";
import { resolveOpenGraphImage } from "@/sanity/lib/utils"; import { resolveOpenGraphImage } from "@/sanity/lib/utils";
type Props = { type Props = {
params: { slug: string }; params: Promise<{ slug: string }>;
}; };
const postSlugs = defineQuery( const postSlugs = defineQuery(
...@@ -36,7 +36,11 @@ export async function generateMetadata( ...@@ -36,7 +36,11 @@ export async function generateMetadata(
{ params }: Props, { params }: Props,
parent: ResolvingMetadata, parent: ResolvingMetadata,
): Promise<Metadata> { ): Promise<Metadata> {
const post = await sanityFetch({ query: postQuery, params, stega: false }); const post = await sanityFetch({
query: postQuery,
params,
stega: false,
});
const previousImages = (await parent).openGraph?.images || []; const previousImages = (await parent).openGraph?.images || [];
const ogImage = resolveOpenGraphImage(post?.coverImage); const ogImage = resolveOpenGraphImage(post?.coverImage);
......
import { defineEnableDraftMode } from "next-sanity/draft-mode";
import { client } from "@/sanity/lib/client";
import { token } from "@/sanity/lib/token";
export const { GET } = defineEnableDraftMode({
client: client.withConfig({ token }),
});
/**
* This file is used to allow Presentation to set the app in Draft Mode, which will load Visual Editing
* and query draft content and preview the content as it will appear once everything is published
*/
import { validatePreviewUrl } from "@sanity/preview-url-secret";
import { draftMode } from "next/headers";
import { redirect } from "next/navigation";
import { client } from "@/sanity/lib/client";
import { token } from "@/sanity/lib/token";
const clientWithToken = client.withConfig({ token });
export async function GET(request: Request) {
const { isValid, redirectTo = "/" } = await validatePreviewUrl(
clientWithToken,
request.url,
);
if (!isValid) {
return new Response("Invalid secret", { status: 401 });
}
draftMode().enable();
redirect(redirectTo);
}
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
// Used to guard against accidentally leaking SANITY_API_READ_TOKEN to the browser
taint: true,
},
logging: {
fetches: { fullUrl: false },
},
};
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
env: {
// Matches the behavior of `sanity dev` which sets styled-components to use the fastest way of inserting CSS rules in both dev and production. It's default behavior is to disable it in dev mode.
SC_DISABLE_SPEEDY: "false",
},
};
export default nextConfig;
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
"private": true, "private": true,
"scripts": { "scripts": {
"predev": "npm run typegen", "predev": "npm run typegen",
"dev": "next", "dev": "next --turbo",
"prebuild": "npm run typegen", "prebuild": "npm run typegen",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
...@@ -13,32 +13,32 @@ ...@@ -13,32 +13,32 @@
"typegen": "sanity schema extract && sanity typegen generate" "typegen": "sanity schema extract && sanity typegen generate"
}, },
"dependencies": { "dependencies": {
"@sanity/assist": "^3.0.6", "@sanity/assist": "^3.0.8",
"@sanity/icons": "^3.3.1", "@sanity/icons": "^3.4.0",
"@sanity/image-url": "^1.0.2", "@sanity/image-url": "^1.0.2",
"@sanity/preview-url-secret": "^1.6.20", "@sanity/preview-url-secret": "^2.0.0",
"@sanity/vision": "^3.55.0", "@sanity/vision": "^3.62.0",
"@tailwindcss/typography": "^0.5.14", "@tailwindcss/typography": "^0.5.15",
"@types/node": "^20.14.13", "@types/node": "^22.7.8",
"@types/react": "^18.3.4", "@types/react": "^18.3.11",
"@types/react-dom": "^18.3.0", "@types/react-dom": "^18.3.1",
"@vercel/speed-insights": "^1.0.12", "@vercel/speed-insights": "^1.0.13",
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
"date-fns": "^3.6.0", "date-fns": "^4.1.0",
"next": "^14.2.5", "next": "^15.0.0",
"next-sanity": "^9.4.7", "next-sanity": "^9.7.0",
"postcss": "^8.4.41", "postcss": "^8.4.47",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"sanity": "^3.55.0", "sanity": "^3.62.0",
"sanity-plugin-asset-source-unsplash": "^3.0.1", "sanity-plugin-asset-source-unsplash": "^3.0.1",
"server-only": "^0.0.1", "server-only": "^0.0.1",
"styled-components": "^6.1.12", "styled-components": "^6.1.13",
"tailwindcss": "^3.4.10", "tailwindcss": "^3.4.14",
"typescript": "5.5.4" "typescript": "5.6.3"
}, },
"devDependencies": { "devDependencies": {
"eslint": "^8.57.0", "eslint": "^9.13.0",
"eslint-config-next": "^14.2.5" "eslint-config-next": "^15.0.0"
} }
} }
...@@ -71,7 +71,7 @@ export default defineConfig({ ...@@ -71,7 +71,7 @@ export default defineConfig({
}), }),
}, },
}, },
previewUrl: { previewMode: { enable: "/api/draft" } }, previewUrl: { previewMode: { enable: "/api/draft-mode/enable" } },
}), }),
structureTool({ structure: pageStructure([settings]) }), structureTool({ structure: pageStructure([settings]) }),
// Configures the global "new document" button, and document actions, to suit the Settings document singleton // Configures the global "new document" button, and document actions, to suit the Settings document singleton
......
...@@ -13,22 +13,29 @@ import { token } from "@/sanity/lib/token"; ...@@ -13,22 +13,29 @@ import { token } from "@/sanity/lib/token";
export async function sanityFetch<const QueryString extends string>({ export async function sanityFetch<const QueryString extends string>({
query, query,
params = {}, params = {},
perspective = draftMode().isEnabled ? "previewDrafts" : "published", perspective: _perspective,
/** /**
* Stega embedded Content Source Maps are used by Visual Editing by both the Sanity Presentation Tool and Vercel Visual Editing. * Stega embedded Content Source Maps are used by Visual Editing by both the Sanity Presentation Tool and Vercel Visual Editing.
* The Sanity Presentation Tool will enable Draft Mode when loading up the live preview, and we use it as a signal for when to embed source maps. * The Sanity Presentation Tool will enable Draft Mode when loading up the live preview, and we use it as a signal for when to embed source maps.
* When outside of the Sanity Studio we also support the Vercel Toolbar Visual Editing feature, which is only enabled in production when it's a Vercel Preview Deployment. * When outside of the Sanity Studio we also support the Vercel Toolbar Visual Editing feature, which is only enabled in production when it's a Vercel Preview Deployment.
*/ */
stega = perspective === "previewDrafts" || stega: _stega,
process.env.VERCEL_ENV === "preview",
}: { }: {
query: QueryString; query: QueryString;
params?: QueryParams; params?: QueryParams | Promise<QueryParams>;
perspective?: Omit<ClientPerspective, "raw">; perspective?: Omit<ClientPerspective, "raw">;
stega?: boolean; stega?: boolean;
}) { }) {
const perspective =
_perspective || (await draftMode()).isEnabled
? "previewDrafts"
: "published";
const stega =
_stega ||
perspective === "previewDrafts" ||
process.env.VERCEL_ENV === "preview";
if (perspective === "previewDrafts") { if (perspective === "previewDrafts") {
return client.fetch(query, params, { return client.fetch(query, await params, {
stega, stega,
perspective: "previewDrafts", perspective: "previewDrafts",
// The token is required to fetch draft content // The token is required to fetch draft content
...@@ -39,7 +46,7 @@ export async function sanityFetch<const QueryString extends string>({ ...@@ -39,7 +46,7 @@ export async function sanityFetch<const QueryString extends string>({
next: { revalidate: 0 }, next: { revalidate: 0 },
}); });
} }
return client.fetch(query, params, { return client.fetch(query, await params, {
stega, stega,
perspective: "published", perspective: "published",
// The `published` perspective is available on the API CDN // The `published` perspective is available on the API CDN
......
import "server-only"; import "server-only";
import { experimental_taintUniqueValue } from "react";
export const token = process.env.SANITY_API_READ_TOKEN; export const token = process.env.SANITY_API_READ_TOKEN;
if (!token) { if (!token) {
throw new Error("Missing SANITY_API_READ_TOKEN"); throw new Error("Missing SANITY_API_READ_TOKEN");
} }
experimental_taintUniqueValue(
"Do not pass the sanity API read token to the client.",
process,
token,
);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment