Schema UI: Next.js + Sanity Starter Template

repository·master·Indexed 40 days ago

https://github.com/serge-0v/next-js-sanity-starter

A production-ready monorepo starter template combining Next.js for the frontend and Sanity Studio for content management. Designed for rapid development of content-driven websites using the Schema UI component library, it includes pre-configured Sanity clients, TypeGen for TypeScript synchronization, and support for Sanity Live Content API.

Tokens
6.5K
Snippets
27
Records
30
Agent score
100%

What's inside Schema UI Next.js Sanity Starter

  1. Understand the Monorepo layout

    master

    The project is organized as a pnpm workspace with two main applications. Most commands should be run from the repository root.

    PathRole
    frontend/Next.js application containing pages, API routes, and generated sanity.types.ts
    studio/Sanity Studio application containing schemas, sanity CLI commands, and sample data

    Note: When running locally, the Studio runs at http://localhost:3333 and the Next.js app runs at http://localhost:3000.

  2. Deploy the Next.js application to Vercel

    master

    When deploying the frontend to Vercel, follow these specific configuration steps:

    1. Root Directory: Set the Vercel project Root Directory to frontend.
    2. Environment Variables: Copy all variables from frontend/.env.local to Vercel.
    3. Studio URL: Ensure you include NEXT_PUBLIC_STUDIO_URL pointing to your hosted Studio URL (without a trailing slash).
    4. CORS: Add your production Vercel URL to the CORS Origins in your Sanity project settings.
  3. Import sample data into Sanity

    master

    To populate your Studio with demo content, import the provided sample data archive. This must be run from the studio directory.

    Warning: Using the --replace flag will overwrite all existing data in your dataset.

    cd studio
    sanity dataset import sample-data.tar.gz production --replace
  4. Run the template locally

    master

    From the repository root, use the following commands to start your development environment:

    • Start both apps: pnpm dev (Starts Next.js and Studio)
    • Start frontend only: pnpm dev:frontend
    • Start studio only: pnpm dev:studio

    Local Configuration for Previews: To ensure draft mode and Presentation previews work correctly, set these variables in your local .env files:

    • In frontend/.env.local: NEXT_PUBLIC_STUDIO_URL=http://localhost:3333
    • In studio/.env.local: SANITY_STUDIO_PREVIEW_URL=http://localhost:3000
    pnpm dev
  5. Generate Sanity types with TypeGen

    master

    To keep your Next.js frontend in sync with your Sanity schemas and queries, you must run TypeGen. This generates frontend/sanity.types.ts.

    From the repository root:

    pnpm typegen

    Manual steps

    From the studio directory:

    1. Extract schema: npx sanity schema extract (generates studio/schema.json)
    2. Generate types: npx sanity typegen generate (generates frontend/sanity.types.ts)
  6. Deploy Sanity Studio

    master

    You can deploy the Studio to *.sanity.studio or to Vercel.

    Deploy to Sanity Cloud

    From the studio directory:

    cd studio
    sanity deploy

    Note: After the first deploy, save the SANITY_STUDIO_APP_ID provided by the CLI to skip the hostname prompt in future deploys.

    Deploy to Vercel (Optional)

    Create a separate Vercel project with the Root Directory set to studio and provide the environment variables found in studio/.env.local.

  7. Install the Schema UI template

    master

    You can initialize the template using the Sanity CLI, which automates project creation, CORS configuration, and environment variable setup, or by manually cloning the repository.

    Run this command to bootstrap a new project:

    npm create sanity@latest -- --template serge-0v/next-js-sanity-starter

    Option 2: Manual Clone

    1. Clone the repository:
    git clone https://github.com/serge-0v/next-js-js-sanity-starter.git
    cd next-js-sanity-starter
    pnpm install
    1. Create a project in Sanity Manage.
    2. Add CORS origins for http://localhost:3000 and http://localhost:3333.
    3. Copy .env.local.example files from frontend/ and studio/ to .env.local in their respective directories, filling in your project ID, dataset, and tokens.
  8. Manage Singleton Document Types and Actions

    master

    This project uses a pattern to treat specific document types as singletons (e.g., settings or navigation). This is achieved through two configuration steps in defineConfig:

    1. Filtering Templates: The schema.templates function is used to filter out singleton types from the global "New document" menu, preventing users from creating multiple instances of a singleton.
    2. Restricting Actions: The document.actions function filters the available actions for a document based on whether it is a singleton. Only actions defined in the singletonActions set (such as publish, discardChanges, restore, and unpublish) are permitted for singleton types.

    To add a new singleton, add its schema type name to the singletonTypes Set and ensure its allowed actions are in the singletonActions Set.

    const singletonActions = new Set([
      "publish",
      "discardChanges",
      "restore",
      "unpublish",
    ]);
    
    const singletonTypes = new Set(["settings", "navigation"]);
    
    // Inside defineConfig...
    // ...
      schema: {
        types: schemaTypes,
        templates: (templates) =>
          templates.filter(({ schemaType }) => !singletonTypes.has(schemaType)),
      },
      document: {
        actions: (input, context) =>
          singletonTypes.has(context.schemaType)
            ? input.filter(({ action }) => action && singletonActions.has(action))
            : input,
      },
    // ...
  9. Configure Sanity Studio via defineConfig

    master

    The Sanity Studio is configured using the defineConfig function. This configuration manages project connection details, content schemas, document actions, and available plugins.

    Environment Variables

    The configuration relies on the following environment variables:

    • SANITY_STUDIO_PROJECT_ID: Your Sanity project ID.
    • SANITY_STUDIO_DATASET: The dataset to use (defaults to production).
    • SANITY_STUDIO_API_VERSION: The API version for Sanity queries (defaults to 2026-03-23).
    • SANITY_STUDIO_PREVIEW_URL: The URL of your Next.js application used for the Presentation tool (defaults to http://localhost:3000).
    import { defineConfig } from "sanity";
    
    export default defineConfig({
      title: "Schema UI: Starter",
      projectId: process.env.SANITY_STUDIO_PROJECT_ID,
      dataset: process.env.SANITY_STUDIO_DATASET,
      // ... other config
    });
  10. Configure Next.js environment variables

    master

    Set up the following environment variables in frontend/.env.local to configure the Next.js frontend. These variables control site metadata, Sanity connectivity, and newsletter functionality.

    NEXT_PUBLIC_SITE_URL - your website url (e.g., https://yourwebsite.com, no trailing slash). Used for sitemap.ts, robots.ts, and client.ts.
    NEXT_PUBLIC_SITE_ENV - environment type (development/production). Setting to "development" prevents search engine indexing.
    NEXT_PUBLIC_STUDIO_URL - your Sanity Studio url (e.g., https://your-sanity-hostname.sanity.studio or http://localhost:3333, no trailing slash).
    NEXT_PUBLIC_SANITY_API_VERSION - Sanity API version in YYYY-MM-DD format.
    NEXT_PUBLIC_SANITY_PROJECT_ID - your Sanity project ID (e.g., abc12345).
    NEXT_PUBLIC_SANITY_DATASET - your Sanity dataset name (e.g., production).
    SANITY_API_READ_TOKEN - Sanity read token for data fetching.
    RESEND_API_KEY - RESEND API key for the newsletter form.
    RESEND_AUDIENCE_ID - RESEND audience ID for the newsletter form.
  11. Manage workspace packages with pnpm

    master

    Use the following commands from the repository root to manage dependencies across the monorepo.

    Installing packages

    • To frontend: pnpm add <package-name> --filter frontend
    • To studio: pnpm add <package-name> --filter studio
    • To root: pnpm add -w <package-name>

    Updating dependencies

    • Update everything: pnpm up --latest --recursive
    • Update frontend only: pnpm up --latest --filter frontend
    • Update studio only: pnpm up --latest --filter studio
  12. Configure Sanity Studio environment variables

    master

    Set up the following environment variables in studio/.env.local to configure the Sanity Studio. These variables are essential for preview modes, deployment, and authentication.

    SANITY_STUDIO_PREVIEW_URL - your Next.js site url for preview (e.g., https://yourwebsite.com or http://localhost:3000, no trailing slash).
    SANITY_STUDIO_PROJECT_ID - your Sanity project ID (e.g., abc12345).
    SANITY_STUDIO_DATASET - your Sanity dataset name (e.g., production).
    SANITY_STUDIO_HOSTNAME - your Sanity Studio hostname for `sanity deploy` (unique on .sanity.studio).
    SANITY_STUDIO_API_VERSION - Sanity API version in YYYY-MM-DD format.
    SANITY_AUTH_TOKEN - Sanity auth token for Studio deploy via GitHub Actions (Generate in Sanity Manage → API → Tokens with deploy permission).
    SANITY_STUDIO_APP_ID - your Sanity Studio app ID from the first `sanity deploy`; avoids repeated hostname prompts.