Unverified Commit 9d30f43a authored by Snorre Eskeland Brekke's avatar Snorre Eskeland Brekke Committed by GitHub

Updates cms-sanity example to use Sanity v3 (#45662

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

Fixes issues reported, for instance here:
https://github.com/vercel/community/discussions/1449
(The example does not deploy atm and uses an old version of Sanity).
## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [x] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`]

* Updates the Sanity studio to use the latest v3 version. This required
changing some files, as per migrating to Studio v3 docs.
* Updated the README to reflect the changed procedure. 
* Update the next app to use the latest version of next-sanity. Changed
related code as a result.

### Testing
Tested using this deploy url (uses the branch from the forke repo):

https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsanity-io%2Fnext.js%2Ftree%2Fsanity-v3%2Fexamples%2Fcms-sanity&repository-name=cms-sanity&project-name=cms-sanity&demo-title=Blog+using+Next.js+%26+Sanity&demo-description=On-demand+ISR%2C+sub-second+as-you-type+previews&demo-url=https%3A%2F%2Fnext-blog-sanity.vercel.app%2F&demo-image=https%3A%2F%2Fuser-images.githubusercontent.com%2F110497645%2F182727236-75c02b1b-faed-4ae2-99ce-baa089f7f363.png&integration-ids=oac_hb2LITYajhRQ0i4QznmKH7gx


## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)

fixes #46450
parent f3ef4e99
...@@ -37,18 +37,17 @@ You'll get: ...@@ -37,18 +37,17 @@ You'll get:
# Configuration # Configuration
- [Step 1. Set up the environment](#step-1-set-up-the-environment) - [Step 1. Set up the environment](#step-1-set-up-the-environment)
- [Step 2. Configure CORS for localhost](#step-2-configure-cors-for-localhost) - [Step 2. Run Next.js locally in development mode](#step-3-run-nextjs-locally-in-development-mode)
- [Step 3. Run Next.js locally in development mode](#step-3-run-nextjs-locally-in-development-mode) - [Step 3. Populate content](#step-3-populate-content)
- [Step 4. Populate content](#step-4-populate-content) - [Step 4. Deploy to production & use Preview Mode from anywhere](#step-4-deploy-to-production--use-preview-mode-from-anywhere)
- [Step 5. Deploy to production & use Preview Mode from anywhere](#step-5-deploy-to-production--use-preview-mode-from-anywhere)
- [If you didn't Deploy with Vercel earlier do so now](#if-you-didnt-deploy-with-vercel-earlier-do-so-now) - [If you didn't Deploy with Vercel earlier do so now](#if-you-didnt-deploy-with-vercel-earlier-do-so-now)
- [Configure CORS for production](#configure-cors-for-production) - [Configure CORS for production](#configure-cors-for-production)
- [Add the preview secret environment variable](#add-the-preview-secret-environment-variable) - [Add the preview secret environment variable](#add-the-preview-secret-environment-variable)
- [How to test locally that the secret is setup correctly](#how-to-test-locally-that-the-secret-is-setup-correctly) - [How to test locally that the secret is setup correctly](#how-to-test-locally-that-the-secret-is-setup-correctly)
- [How to start Preview Mode for Next.js in production from a local Studio](#how-to-start-preview-mode-for-nextjs-in-production-from-a-local-studio) - [How to start Preview Mode for Next.js in production from a local Studio](#how-to-start-preview-mode-for-nextjs-in-production-from-a-local-studio)
- [If you regret sending a preview link to someone](#if-you-regret-sending-a-preview-link-to-someone) - [If you regret sending a preview link to someone](#if-you-regret-sending-a-preview-link-to-someone)
- [Step 6. Deploy your Studio and publish from anywhere](#step-6-deploy-your-studio-and-publish-from-anywhere) - [Step 5. Deploy your Studio and publish from anywhere](#step-5-deploy-your-studio-and-publish-from-anywhere)
- [Step 7. Setup Revalidation Webhook](#step-7-setup-revalidation-webhook) - [Step 6. Setup Revalidation Webhook](#step-6-setup-revalidation-webhook)
- [Testing the Webhook](#testing-the-webhook) - [Testing the Webhook](#testing-the-webhook)
- [Next steps](#next-steps) - [Next steps](#next-steps)
...@@ -71,81 +70,7 @@ Download the environment variables needed to connect Next.js and Studio to your ...@@ -71,81 +70,7 @@ Download the environment variables needed to connect Next.js and Studio to your
npx vercel env pull npx vercel env pull
``` ```
<details> ## Step 2. Run Next.js locally in development mode
<summary>You can also set up manually</summary>
- [Bootstrap the example](#bootstrap-the-example)
- [Connect to a Sanity project](#connect-to-a-sanity-project)
- [Set up environment variables](#set-up-environment-variables)
If using the [integration] isn't an option. Or maybe you want to work locally first and deploy to Vercel later. Whatever the reason this guide shows you how to setup manually.
### Bootstrap the example
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io):
```bash
npx create-next-app --example cms-sanity cms-sanity-app
```
```bash
yarn create next-app --example cms-sanity cms-sanity-app
```
```bash
pnpm create next-app --example cms-sanity cms-sanity-app
```
### Connect to a Sanity project
Run this to select from your existing Sanity projects, or create a new one:
```bash
(cd studio && npx @sanity/cli init)
```
The CLI will update [`sanity.json`] with the project ID and dataset name.
### Set up environment variables
Copy the [`.env.local.example`] file in this directory to `.env.local` (which will be ignored by Git):
```bash
cp .env.local.example .env.local
```
Then set these variables in `.env.local`:
- `NEXT_PUBLIC_SANITY_PROJECT_ID` should be the `projectId` value from [`sanity.json`].
- `NEXT_PUBLIC_SANITY_DATASET` should be the `dataset` value from [`sanity.json`].
- `SANITY_API_READ_TOKEN` create an API token with `read-only` permissions:
- Run this to open your project settings or go to https://manage.sanity.io/ and open your project:
```bash
(cd studio && npx @sanity/cli manage)
```
- Go to **API** and the **Tokens** section at the bottom, launch its **Add API token** button.
- Name it `SANITY_API_READ_TOKEN`, set **Permissions** to `Viewer`.
- Hit **Save** and you can copy/paste the token.
Your `.env.local` file should look like this:
```bash
NEXT_PUBLIC_SANITY_PROJECT_ID=...
NEXT_PUBLIC_SANITY_DATASET=...
SANITY_API_READ_TOKEN=...
```
</details>
## Step 2. Configure CORS for localhost
Needed for live previewing unpublished/draft content.
```bash
npm --prefix studio run cors:add -- http://localhost:3000 --credentials
```
## Step 3. Run Next.js locally in development mode
```bash ```bash
npm install && npm run dev npm install && npm run dev
...@@ -157,6 +82,8 @@ yarn install && yarn dev ...@@ -157,6 +82,8 @@ yarn install && yarn dev
Your blog should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions). Your blog should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions).
Note: This also installs dependencies for Sanity Studio as a post-install step.
## Step 4. Populate content ## Step 4. Populate content
In another terminal start up the studio: In another terminal start up the studio:
...@@ -167,6 +94,8 @@ npm run studio:dev ...@@ -167,6 +94,8 @@ npm run studio:dev
Your studio should be up and running on [http://localhost:3333](http://localhost:3333)! Your studio should be up and running on [http://localhost:3333](http://localhost:3333)!
### Create content
Create content in Sanity Studio and live preview it in Next.js, side-by-side, by opening these URLs: Create content in Sanity Studio and live preview it in Next.js, side-by-side, by opening these URLs:
- [`http://localhost:3333`](http://localhost:3333) - [`http://localhost:3333`](http://localhost:3333)
...@@ -216,7 +145,7 @@ We're all set to do some content creation! ...@@ -216,7 +145,7 @@ We're all set to do some content creation!
To exit Preview Mode, you can click on _"Click here to exit preview mode"_ at the top. To exit Preview Mode, you can click on _"Click here to exit preview mode"_ at the top.
## Step 5. Deploy to production & use Preview Mode from anywhere ## Step 4. Deploy to production & use Preview Mode from anywhere
### If you didn't [Deploy with Vercel earlier](#step-1-set-up-the-environment) do so now ### If you didn't [Deploy with Vercel earlier](#step-1-set-up-the-environment) do so now
...@@ -317,7 +246,7 @@ npx vercel env add SANITY_STUDIO_PREVIEW_SECRET ...@@ -317,7 +246,7 @@ npx vercel env add SANITY_STUDIO_PREVIEW_SECRET
npx vercel --prod npx vercel --prod
``` ```
## Step 6. Deploy your Studio and publish from anywhere ## Step 5. Deploy your Studio and publish from anywhere
Live previewing content is fun, but collaborating on content in real-time is next-level: Live previewing content is fun, but collaborating on content in real-time is next-level:
...@@ -344,7 +273,7 @@ Success! Studio deployed to https://cms-sanity.sanity.studio/ ...@@ -344,7 +273,7 @@ Success! Studio deployed to https://cms-sanity.sanity.studio/
This snippet is stripped from verbose information, you'll see a lot of extra stuff in your terminal. This snippet is stripped from verbose information, you'll see a lot of extra stuff in your terminal.
## Step 7. Setup Revalidation Webhook ## Step 6. Setup Revalidation Webhook
Using GROQ Webhooks Next.js can rebuild pages that have changed content. It rebuilds so fast it can almost compete with Preview Mode. Using GROQ Webhooks Next.js can rebuild pages that have changed content. It rebuilds so fast it can almost compete with Preview Mode.
...@@ -373,7 +302,7 @@ npx vercel --prod ...@@ -373,7 +302,7 @@ npx vercel --prod
Wormhole into the [manager](https://manage.sanity.io/) by running: Wormhole into the [manager](https://manage.sanity.io/) by running:
```bash ```bash
(cd studio && npx @sanity/cli hook create) (cd studio && npx sanity hook create)
``` ```
- **Name** it "On-demand Revalidation". - **Name** it "On-demand Revalidation".
......
...@@ -12,7 +12,6 @@ export default function CoverImage({ title, slug, image: source, priority }) { ...@@ -12,7 +12,6 @@ export default function CoverImage({ title, slug, image: source, priority }) {
> >
<Image <Image
className="w-full h-auto" className="w-full h-auto"
layout="responsive"
width={2000} width={2000}
height={1000} height={1000}
alt={`Cover Image for ${title}`} alt={`Cover Image for ${title}`}
......
import { usePreview } from '../lib/sanity'
import { indexQuery } from '../lib/queries'
import Landing from './landing'
export default function LandingPreview({ allPosts }) {
const previewAllPosts = usePreview(null, indexQuery)
return <Landing data={previewAllPosts ?? allPosts} preview />
}
import Layout from './layout'
import Head from 'next/head'
import { CMS_NAME } from '../lib/constants'
import Container from './container'
import Intro from './intro'
import HeroPost from './hero-post'
import MoreStories from './more-stories'
export default function Landing({ allPosts, preview }) {
const [heroPost, ...morePosts] = allPosts || []
return (
<>
<Layout preview={preview}>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.title}
coverImage={heroPost.coverImage}
date={heroPost.date}
author={heroPost.author}
slug={heroPost.slug}
excerpt={heroPost.excerpt}
/>
)}
{morePosts.length > 0 && <MoreStories posts={morePosts} />}
</Container>
</Layout>
</>
)
}
import PostPreview from '../components/post-preview' import PostPlug from './post-plug'
export default function MoreStories({ posts }) { export default function MoreStories({ posts }) {
return ( return (
...@@ -8,7 +8,7 @@ export default function MoreStories({ posts }) { ...@@ -8,7 +8,7 @@ export default function MoreStories({ posts }) {
</h2> </h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32"> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
{posts.map((post) => ( {posts.map((post) => (
<PostPreview <PostPlug
key={post.slug} key={post.slug}
title={post.title} title={post.title}
coverImage={post.coverImage} coverImage={post.coverImage}
......
import Avatar from '../components/avatar'
import Date from '../components/date'
import CoverImage from './cover-image'
import Link from 'next/link'
export default function PostPlug({
title,
coverImage,
date,
excerpt,
author,
slug,
}) {
return (
<div>
<div className="mb-5">
<CoverImage slug={slug} title={title} image={coverImage} />
</div>
<h3 className="mb-3 text-3xl leading-snug">
<Link href={`/posts/${slug}`} className="hover:underline">
{title}
</Link>
</h3>
<div className="mb-4 text-lg">
<Date dateString={date} />
</div>
<p className="mb-4 text-lg leading-relaxed">{excerpt}</p>
{author && <Avatar name={author.name} picture={author.picture} />}
</div>
)
}
import Avatar from '../components/avatar' import { usePreview } from '../lib/sanity'
import Date from '../components/date' import { postQuery } from '../lib/queries'
import CoverImage from './cover-image' import Post from './post'
import Link from 'next/link'
export default function PostPreview({ export default function PostPreview({ data }) {
title, const slug = data?.post?.slug
coverImage, const previewData = usePreview(null, postQuery, { slug })
date, return <Post data={previewData ?? data} preview />
excerpt,
author,
slug,
}) {
return (
<div>
<div className="mb-5">
<CoverImage slug={slug} title={title} image={coverImage} />
</div>
<h3 className="mb-3 text-3xl leading-snug">
<Link href={`/posts/${slug}`} className="hover:underline">
{title}
</Link>
</h3>
<div className="mb-4 text-lg">
<Date dateString={date} />
</div>
<p className="mb-4 text-lg leading-relaxed">{excerpt}</p>
{author && <Avatar name={author.name} picture={author.picture} />}
</div>
)
} }
import { useRouter } from 'next/router'
import { urlForImage } from '../lib/sanity'
import ErrorPage from 'next/error'
import Layout from './layout'
import Container from './container'
import Header from './header'
import PostTitle from './post-title'
import Head from 'next/head'
import { CMS_NAME } from '../lib/constants'
import PostHeader from './post-header'
import PostBody from './post-body'
import SectionSeparator from './section-separator'
import MoreStories from './more-stories'
export default function Post({ data = {}, preview = false }) {
const router = useRouter()
const { post, morePosts } = data
const slug = post?.slug
if (!router.isFallback && !slug) {
return <ErrorPage statusCode={404} />
}
return (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
) : (
<>
<article>
<Head>
<title>
{`${post.title} | Next.js Blog Example with ${CMS_NAME}`}
</title>
{post.coverImage?.asset?._ref && (
<meta
key="ogImage"
property="og:image"
content={urlForImage(post.coverImage)
.width(1200)
.height(627)
.fit('crop')
.url()}
/>
)}
</Head>
<PostHeader
title={post.title}
coverImage={post.coverImage}
date={post.date}
author={post.author}
/>
<PostBody content={post.content} />
</article>
<SectionSeparator />
{morePosts.length > 0 && <MoreStories posts={morePosts} />}
</>
)}
</Container>
</Layout>
)
}
import createImageUrlBuilder from '@sanity/image-url' import createImageUrlBuilder from '@sanity/image-url'
import { createPreviewSubscriptionHook } from 'next-sanity' import { definePreview } from 'next-sanity/preview'
import { sanityConfig } from './config' import { sanityConfig } from './config'
export const imageBuilder = createImageUrlBuilder(sanityConfig) export const imageBuilder = createImageUrlBuilder(sanityConfig)
...@@ -7,5 +7,7 @@ export const imageBuilder = createImageUrlBuilder(sanityConfig) ...@@ -7,5 +7,7 @@ export const imageBuilder = createImageUrlBuilder(sanityConfig)
export const urlForImage = (source) => export const urlForImage = (source) =>
imageBuilder.image(source).auto('format').fit('max') imageBuilder.image(source).auto('format').fit('max')
export const usePreviewSubscription = export const usePreview = definePreview({
createPreviewSubscriptionHook(sanityConfig) projectId: sanityConfig.projectId,
dataset: sanityConfig.dataset,
})
...@@ -8,19 +8,19 @@ ...@@ -8,19 +8,19 @@
"studio:deploy": "npx vercel env pull && npm --prefix studio run deploy" "studio:deploy": "npx vercel env pull && npm --prefix studio run deploy"
}, },
"dependencies": { "dependencies": {
"@portabletext/react": "^1.0.6", "@portabletext/react": "^2.0.1",
"@sanity/image-url": "^1.0.1", "@sanity/image-url": "^1.0.2",
"@sanity/webhook": "^2.0.0", "@sanity/webhook": "^2.0.0",
"classnames": "^2.3.1", "classnames": "^2.3.1",
"date-fns": "^2.29.1", "date-fns": "^2.29.3",
"next": "latest", "next": "latest",
"next-sanity": "^0.6.0", "next-sanity": "^4.1.2",
"react": "^18.2.0", "react": "^18",
"react-dom": "^18.2.0" "react-dom": "^18"
}, },
"devDependencies": { "devDependencies": {
"autoprefixer": "^10.4.8", "autoprefixer": "^10.4.13",
"postcss": "^8.4.14", "postcss": "^8.4.21",
"tailwindcss": "^3.1.7" "tailwindcss": "^3.2.4"
} }
} }
import Head from 'next/head'
import Container from '../components/container'
import MoreStories from '../components/more-stories'
import HeroPost from '../components/hero-post'
import Intro from '../components/intro'
import Layout from '../components/layout'
import { CMS_NAME } from '../lib/constants'
import { indexQuery } from '../lib/queries' import { indexQuery } from '../lib/queries'
import { usePreviewSubscription } from '../lib/sanity'
import { getClient, overlayDrafts } from '../lib/sanity.server' import { getClient, overlayDrafts } from '../lib/sanity.server'
import { PreviewSuspense } from 'next-sanity/preview'
import { lazy } from 'react'
import Landing from '../components/landing'
export default function Index({ allPosts: initialAllPosts, preview }) { const LandingPreview = lazy(() => import('../components/landing-preview'))
const { data: allPosts } = usePreviewSubscription(indexQuery, {
initialData: initialAllPosts, export default function IndexPage({ allPosts, preview }) {
enabled: preview, if (preview) {
})
const [heroPost, ...morePosts] = allPosts || []
return ( return (
<> <PreviewSuspense fallback="Loading...">
<Layout preview={preview}> <LandingPreview allPosts={allPosts} />
<Head> </PreviewSuspense>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.title}
coverImage={heroPost.coverImage}
date={heroPost.date}
author={heroPost.author}
slug={heroPost.slug}
excerpt={heroPost.excerpt}
/>
)}
{morePosts.length > 0 && <MoreStories posts={morePosts} />}
</Container>
</Layout>
</>
) )
}
return <Landing allPosts={allPosts} />
} }
export async function getStaticProps({ preview = false }) { export async function getStaticProps({ preview = false }) {
......
import Head from 'next/head' import { lazy } from 'react'
import { useRouter } from 'next/router' import { PreviewSuspense } from 'next-sanity/preview'
import ErrorPage from 'next/error'
import Container from '../../components/container'
import PostBody from '../../components/post-body'
import MoreStories from '../../components/more-stories'
import Header from '../../components/header'
import PostHeader from '../../components/post-header'
import SectionSeparator from '../../components/section-separator'
import Layout from '../../components/layout'
import PostTitle from '../../components/post-title'
import { CMS_NAME } from '../../lib/constants'
import { postQuery, postSlugsQuery } from '../../lib/queries' import { postQuery, postSlugsQuery } from '../../lib/queries'
import { urlForImage, usePreviewSubscription } from '../../lib/sanity' import { getClient, overlayDrafts, sanityClient } from '../../lib/sanity.server'
import { sanityClient, getClient, overlayDrafts } from '../../lib/sanity.server' import Post from '../../components/post'
export default function Post({ data = {}, preview }) { const PostPreview = lazy(() => import('../../components/post-preview'))
const router = useRouter()
const slug = data?.post?.slug
const {
data: { post, morePosts },
} = usePreviewSubscription(postQuery, {
params: { slug },
initialData: data,
enabled: preview && slug,
})
if (!router.isFallback && !slug) {
return <ErrorPage statusCode={404} />
}
export default function PostPage({ preview, data }) {
if (preview) {
return ( return (
<Layout preview={preview}> <PreviewSuspense fallback="Loading...">
<Container> <PostPreview data={data} />
<Header /> </PreviewSuspense>
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
) : (
<>
<article>
<Head>
<title>
{`${post.title} | Next.js Blog Example with ${CMS_NAME}`}
</title>
{post.coverImage?.asset?._ref && (
<meta
key="ogImage"
property="og:image"
content={urlForImage(post.coverImage)
.width(1200)
.height(627)
.fit('crop')
.url()}
/>
)}
</Head>
<PostHeader
title={post.title}
coverImage={post.coverImage}
date={post.date}
author={post.author}
/>
<PostBody content={post.content} />
</article>
<SectionSeparator />
{morePosts.length > 0 && <MoreStories posts={morePosts} />}
</>
)}
</Container>
</Layout>
) )
}
return <Post data={data} />
} }
export async function getStaticProps({ params, preview = false }) { export async function getStaticProps({ params, preview = false }) {
......
...@@ -30,3 +30,5 @@ yarn-error.log* ...@@ -30,3 +30,5 @@ yarn-error.log*
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts next-env.d.ts
.sanity
{
"#": "Used by Sanity to keep track of configuration file checksums, do not delete or modify!",
"@sanity/default-layout": "bb034f391ba508a6ca8cd971967cbedeb131c4d19b17b28a0895f32db5d568ea",
"@sanity/default-login": "e2ed4e51e97331c0699ba7cf9f67cbf76f1c6a5f806d6eabf8259b2bcb5f1002",
"@sanity/form-builder": "b38478227ba5e22c91981da4b53436df22e48ff25238a55a973ed620be5068aa",
"@sanity/data-aspects": "d199e2c199b3e26cd28b68dc84d7fc01c9186bf5089580f2e2446994d36b3cb6",
"@sanity/vision": "da5b6ed712703ecd04bf4df560570c668aa95252c6bc1c41d6df1bda9b8b8f60"
}
{
"toolSwitcher": {
"order": [],
"hidden": []
}
}
{
"providers": {
"mode": "append",
"redirectOnSingle": false,
"entries": []
},
"loginMethod": "dual"
}
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"start": "npx @sanity/cli start", "start": "sanity dev",
"deploy": "npx @sanity/cli deploy", "dev": "sanity dev",
"cors:add": "npx @sanity/cli cors add", "build": "sanity build",
"cors:add": "npx sanity cors add",
"deploy": "sanity deploy",
"prestart": "npm run env", "prestart": "npm run env",
"precors:add": "npm run env",
"predeploy": "npm run env", "predeploy": "npm run env",
"env": "npx @sanity/cli install && cp ../.env .env.development || cp ../.env.local .env.development" "env": "cp ../.env .env.development || cp ../.env.local .env.development"
}, },
"dependencies": { "dependencies": {
"@sanity/base": "^2.30.1", "sanity": "^3.2.6",
"@sanity/core": "^2.30.2", "@sanity/vision": "^3.2.6",
"@sanity/default-layout": "^2.30.1",
"@sanity/default-login": "^2.30.1",
"@sanity/desk-tool": "^2.30.1",
"@sanity/production-preview": "2.29.3",
"@sanity/vision": "^2.30.1",
"prop-types": "^15.7", "prop-types": "^15.7",
"react": "^17.0", "react": "^18",
"react-dom": "^17.0", "react-dom": "^18",
"sanity-plugin-asset-source-unsplash": "0.2.1", "sanity-plugin-asset-source-unsplash": "^1.0.6",
"styled-components": "^5.2.0" "styled-components": "^5.2.0"
},
"devDependencies": {
"autoprefixer": "^10.4.13",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.4"
} }
} }
let productionUrl let productionUrl
try { try {
productionUrl = new URL( productionUrl = new URL(
process.env.SANITY_STUDIO_PREVIEW_URL || 'http://localhost:3000' import.meta.env.SANITY_STUDIO_PREVIEW_URL || 'http://localhost:3000'
) )
} catch (err) { } catch (err) {
console.error('Invalid productionUrl', err) console.error('Invalid productionUrl', err)
} }
export default function resolveProductionUrl(document) { export function resolveProductionUrl(prev, { document }) {
if (!productionUrl || !document.slug?.current) { if (!productionUrl || !document.slug?.current) {
return false return prev
} }
const searchParams = new URLSearchParams() const searchParams = new URLSearchParams()
searchParams.set('secret', process.env.SANITY_STUDIO_PREVIEW_SECRET || '') searchParams.set('secret', import.meta.env.SANITY_STUDIO_PREVIEW_SECRET || '')
searchParams.set('slug', document.slug.current) searchParams.set('slug', document.slug.current)
return `${productionUrl.origin}/api/preview?${searchParams}` return `${productionUrl.origin}/api/preview?${searchParams}`
} }
import { loadEnvConfig } from '@next/env'
import { defineCliConfig } from 'sanity/cli'
const dev = process.env.NODE_ENV !== 'production'
loadEnvConfig(__dirname, dev, { info: () => null, error: console.error })
const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID
const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET
export default defineCliConfig({
api: { projectId, dataset },
vite: (config) => {
return {
...config,
envPrefix: ['NEXT_', 'SANITY_STUDIO_', 'VITE_'],
}
},
})
import { visionTool } from '@sanity/vision'
import { defineConfig } from 'sanity'
import { deskTool } from 'sanity/desk'
import { unsplashImageAsset } from 'sanity-plugin-asset-source-unsplash'
import { resolveProductionUrl } from './resolveProductionUrl'
import { author } from './schemas/author'
import { post } from './schemas/post'
const title =
import.meta.env.NEXT_PUBLIC_SANITY_PROJECT_TITLE ||
'Next.js Blog with Sanity.io'
const projectId = import.meta.env.NEXT_PUBLIC_SANITY_PROJECT_ID
const dataset = import.meta.env.NEXT_PUBLIC_SANITY_DATASET
export default defineConfig({
basePath: '/',
projectId: projectId || '',
dataset: dataset || '',
title,
schema: {
// If you want more content types, you can add them to this array
types: [author, post],
},
document: {
productionUrl: resolveProductionUrl,
},
plugins: [
deskTool({}),
// Add an image asset source for Unsplash
unsplashImageAsset(),
// Vision lets you query your content with GROQ in the studio
// https://www.sanity.io/docs/the-vision-plugin
visionTool(),
],
})
{
"root": true,
"project": {
"name": "Blog"
},
"plugins": [
"@sanity/base",
"@sanity/default-layout",
"@sanity/default-login",
"@sanity/desk-tool",
"asset-source-unsplash",
"@sanity/production-preview"
],
"env": {
"development": {
"plugins": ["@sanity/vision"]
}
},
"parts": [
{
"name": "part:@sanity/base/schema",
"path": "./schemas/schema"
},
{
"implements": "part:@sanity/production-preview/resolve-production-url",
"path": "./resolveProductionUrl.js"
}
]
}
export default { export const author = {
name: 'author', name: 'author',
title: 'Author', title: 'Author',
type: 'document', type: 'document',
......
export default { export const post = {
name: 'post', name: 'post',
title: 'Post', title: 'Post',
type: 'document', type: 'document',
......
// First, we must import the schema creator
import createSchema from 'part:@sanity/base/schema-creator'
// Then import schema types from any plugins that might expose them
import schemaTypes from 'all:part:@sanity/base/schema-type'
// We import object and document schemas
// import blockContent from './blockContent'
import post from './post'
import author from './author'
// Then we give our schema to the builder and provide the result to Sanity
export default createSchema({
// We name our schema
name: 'default',
// Then proceed to concatenate our document type
// to the ones provided by any plugins that are installed
types: schemaTypes.concat([
/* Your types here! */
post,
author,
]),
})
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./components/**/*.{js,ts,jsx,tsx}'],
theme: {},
plugins: [],
}
{
// Note: This config is only used to help editors like VS Code understand/resolve
// parts, the actual transpilation is done by babel. Any compiler configuration in
// here will be ignored.
"include": [
"./node_modules/@sanity/base/types/**/*.ts",
"./**/*.ts",
"./**/*.tsx"
]
}
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