All Projects → sanity-io → Next Sanity

sanity-io / Next Sanity

Licence: mit
Sanity.io toolkit for Next.js

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Next Sanity

Ran
⚡ RAN! React . GraphQL . Next.js Toolkit ⚡ - SEO-Ready, Production-Ready, SSR, Hot-Reload, CSS-in-JS, Caching, CLI commands and more...
Stars: ✭ 2,128 (+1750.43%)
Mutual labels:  nextjs, toolkit
Nextjs Headless Wordpress
🔥 Nextjs Headless WordPress
Stars: ✭ 110 (-4.35%)
Mutual labels:  nextjs, preview
next-use-contextual-routing
Generate contextual routing / modal routes paths for Next.js
Stars: ✭ 76 (-33.91%)
Mutual labels:  hook, nextjs
Gatsby Source Sanity
Gatsby source plugin for building websites using Sanity.io as a backend.
Stars: ✭ 160 (+39.13%)
Mutual labels:  real-time, preview
Swr
React Hooks for data fetching
Stars: ✭ 20,348 (+17593.91%)
Mutual labels:  hook, nextjs
Dabnet
Depth-wise Asymmetric Bottleneck for Real-time Semantic Segmentation (BMVC2019)
Stars: ✭ 109 (-5.22%)
Mutual labels:  real-time
Vertxui
Pure 100% java reactive-style client-side webpages with POJO traffic, jUnit GUI testing, declarative view-on-model, automatic browser reloading and more.
Stars: ✭ 112 (-2.61%)
Mutual labels:  toolkit
Yolov3 tensorflow
Complete YOLO v3 TensorFlow implementation. Support training on your own dataset.
Stars: ✭ 1,498 (+1202.61%)
Mutual labels:  real-time
Nextjs Wordpress Starter
WebDevStudios Next.js WordPress Starter
Stars: ✭ 104 (-9.57%)
Mutual labels:  nextjs
Fridaandroidtracer
A runnable jar that generate Javascript hook script to hook Android classes.
Stars: ✭ 114 (-0.87%)
Mutual labels:  hook
Composite
A component-based OS
Stars: ✭ 113 (-1.74%)
Mutual labels:  real-time
Iot Technical Guide
🐝 IoT Technical Guide --- 从零搭建高性能物联网平台及物联网解决方案和Thingsboard源码分析 ✨ ✨ ✨ (IoT Platform, SaaS, MQTT, CoAP, HTTP, Modbus, OPC, WebSocket, 物模型,Protobuf, PostgreSQL, MongoDB, Spring Security, OAuth2, RuleEngine, Kafka, Docker)
Stars: ✭ 2,334 (+1929.57%)
Mutual labels:  real-time
Wagtail Pipit
Pipit is a Wagtail CMS boilerplate which aims to provide an easy and modern developer workflow with a React-rendered frontend.
Stars: ✭ 109 (-5.22%)
Mutual labels:  nextjs
Autobahn Java
WebSocket & WAMP in Java for Android and Java 8
Stars: ✭ 1,467 (+1175.65%)
Mutual labels:  real-time
React Smooth Scroll Hook
A React Hook for using smooth scroll in React Component
Stars: ✭ 114 (-0.87%)
Mutual labels:  hook
Sshkit.ex
An Elixir toolkit for performing tasks on one or more servers, built on top of Erlang’s SSH application.
Stars: ✭ 108 (-6.09%)
Mutual labels:  toolkit
Next Cms Ghost
Publish flaring fast blogs with Next.js and Ghost CMS
Stars: ✭ 107 (-6.96%)
Mutual labels:  nextjs
Elm Doc Preview
Elm offline documentation previewer
Stars: ✭ 113 (-1.74%)
Mutual labels:  preview
Vrt
🔅 Ray tracing library for Vulkan API (indev)
Stars: ✭ 111 (-3.48%)
Mutual labels:  real-time
Albumcamerarecorder
一个高效的多媒体支持操作库,可多方面的简单配置操作相册、拍照、录制、录音等功能。也支持配套使用的展示图片、视频、音频的九宫格功能。 (An efficient multimedia support operation library, can be a variety of simple configuration operation album, photo, recording, recording and other functions.Also support supporting the use of the display of pictures, video, audio of the nine grid function.)
Stars: ✭ 106 (-7.83%)
Mutual labels:  preview

next-sanity

Sanity.io toolkit for Next.js.

Features:

  • Client-side live real-time preview for authenticated users
  • Light-weight client for fetching data
  • URL-helper for Sanity’s image pipeline
  • Rich-text component for Portable Text
  • GROQ syntax highlighting

Table of contents

Installation

$ npm install next-sanity
// or
$ yarn add next-sanity

Live real-time preview

You can implement real-time client side preview using createPreviewSubscriptionHook. It works by streaming the whole dataset to the browser, which it keeps updated using listeners and Mendoza patches. When it recieves updates, then the query is run against the client-side datastore using groq-js. This only happens if you're logged in and the hook is configured to run, which means you can use this code in production.

You might want to use Vercel’s approach to previews, which is set up with a serverless functions that takes a preview secret, which in turn redirects you to a page with a preview prop set to true.

Limits

The real-time preview isn't optimized and comes with a configured limit of 3000 documents. You can experiment with larger datasets by configuring the hook with documentLimit: <Integer>. Be aware that this might significantly affect the preview performance.

We have plans for optimizations in the roadmap.

Usage

It’s practical to set up a decicated file where you import and set up your client etc. Below is a comprehensive example of the different things you can set up.

// lib/sanity.js
import {
  groq,
  createClient,
  createImageUrlBuilder,
  createPortableTextComponent,
  createPreviewSubscriptionHook,
  createCurrentUserHook,
} from 'next-sanity'

const config = {
  /**
    * Find your project ID and dataset in `sanity.json` in your studio project.
    * These are considered “public”, but you can use environment variables
    * if you want differ between local dev and production.
    *
    * https://nextjs.org/docs/basic-features/environment-variables
    **/
  dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || 'production',
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
  useCdn: process.env.NODE_ENV === 'production',
  /**
    * Set useCdn to `false` if your application require the freshest possible
    * data always (potentially slightly slower and a bit more expensive).
    * Authenticated request (like preview) will always bypass the CDN
    **/
}

/**
 * Set up a helper function for generating Image URLs with only the asset reference data in your documents.
 * Read more: https://www.sanity.io/docs/image-url
 **/
export const urlFor = source => createImageUrlBuilder(config).image(source)

// Set up the live preview subscription hook
export const usePreviewSubscription = createPreviewSubscriptionHook(config)

// Set up Portable Text serialization
export const PortableText = createPortableTextComponent({
  ...config,
  // Serializers passed to @sanity/block-content-to-react
  // (https://github.com/sanity-io/block-content-to-react)
  serializers: {},
})

// Set up the client for fetching data in the getProps page functions
export const sanityClient = createClient(config)
// Set up a preview client with serverless authentication for drafts
export const previewClient = createClient({
  ...config,
  useCdn: false,
  token: process.env.SANITY_API_TOKEN,
})

// Helper function for easily switching between normal client and preview client
export const getClient = (usePreview) => (usePreview ? previewClient : sanityClient)

// Helper function for using the current logged in user account
export const useCurrentUser = createCurrentUserHook(config)

Example: Minimal blog post template

A minimal example for a blog post template using the schema from from the Sanity Studio blog example. Includes the real-time preview using the configuration illustrated above:

// pages/posts/[slug].js
import ErrorPage from 'next/error'
import {useRouter} from 'next/router'
import {groq} from 'next-sanity'
import {
  getClient,
  usePreviewSubscription,
  urlFor,
  PortableText
  } from '../../lib/sanity'

const postQuery = groq`
  *[_type == "post" && slug.current == $slug][0] {
    _id,
    title,
    body,
    mainImage,
    categories[]->{
      _id,
      title
    },
    "slug": slug.current
  }
`

export default function Post({data, preview}) {
  const router = useRouter()
  if (!router.isFallback && !data.post?.slug) {
    return <ErrorPage statusCode={404} />
  }

  const {data: post} = usePreviewSubscription(postQuery, {
    params: {slug: data.post.slug},
    initialData: data,
    enabled: preview,
  })

  const {title, mainImage, body} = post

  return (
    <article>
      <h2>{title}</h2>
      <figure>
        <img src={urlFor(mainImage).url()} />
      </figure>
      <PortableText blocks={body} />
      <aside>

      </aside>
    </article>
  )
}

export async function getStaticProps({params, preview = false}) {
  const post = await getClient(preview).fetch(postQuery, {
    slug: params.slug,
  })

  return {
    props: {
      preview,
      data: {post},
    },
  }
}

export async function getStaticPaths() {
  const paths = await getClient().fetch(
    groq`*[_type == "post" && defined(slug.current)][].slug.current`
  )

  return {
    paths: paths.map((slug) => ({params: {slug}})),
    fallback: true,
  }
}

License

MIT-licensed. See LICENSE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].