sanity-io / live-content-api-demo-live-blog-nextjs

Demo of how to use Sanity's Live Content API with Next.js and React Server Components

Home Page:https://www.sanity.io/docs/live-content-api

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Live Blog: Sanity Live Content API Example with Next.js

This is a demo of using Sanity's Live Content API to power a live blog.

CleanShot 2024-05-16 at 16 17 40

The Live Content API makes it possible to automatically re-fetch content updates from the Sanity CDN.

In this example, we use a canary of the next-sanity toolkit to import a client that can generate a <LiveSubscription /> component that you can add to any component to make it automatically fetch published content live. It works with React Server Components (no "use client" needed).

This demo relies on Next.js’ searchParams, which must be passed down from the route component.

Try the demo locally

  1. Clone this repo
  2. Install its dependencies (pnpm i)
  3. Run pnpm dlx sanity@latest init --env to create a Sanity project and add the configuration to an .env file
  4. Run pnpm dlx sanity dataset import demo.tar.gz production to import some demo data
  5. Run pnpm dev to start the dev server
  6. If you open http://localhost:3000/studio you will be asked to add it to your project’s CORS origin settings (pnpm dlx sanity cors add http://localhost:3000 --credentials will also do the trick)
  7. And you should be good to go!

Note that this demo uses the experimental (vX) version of the Live Content API, and hence you will get some warnings in your console while you're running it.

Files of note

The following files have interesting stuff relevant to this demo:

  • ./sanity/lib/fetch.ts configures the sanityFetch that returns the <LiveSubscription /> component
  • The following React Server Components have Live Content implemented
    • ./components/Feed.tsx
    • ./components/Speakers.tsx
    • ./components/Schedule.tsx
  • The content model/schema for the Studio is found in ./sanity/schemaTypes

Credits

This demo uses the following things:

About

Demo of how to use Sanity's Live Content API with Next.js and React Server Components

https://www.sanity.io/docs/live-content-api


Languages

Language:TypeScript 95.2%Language:CSS 3.2%Language:JavaScript 1.6%