# Display content in Next.js https://www.sanity.io/learn/course/day-one-with-sanity-studio/bringing-content-to-a-next-js-front-end.md You've now crafted a content creation experience and learned how to query from the Content Lake. All that's left to do is distribute that content to the world. In this lesson, you'll create a new Next.js application and query for Sanity content. Next.js is a React framework for building full-stack web applications. You'll use it in this lesson because of how simply you can get started but the concepts here could work with any framework or front end library. 1. Prefer alternatives to Next.js? [See "clean starter" templates](https://www.sanity.io/templates) available for Astro, React Router and more ## Install a new Next.js application The command below installs a predefined bare bones template with some sensible defaults, and Tailwind CSS is installed. 1. **Run** the following command at the root `day-one` directory to create a new Next.js application. ```sh # in the root /day-one directory pnpm dlx create-next-app@latest apps/web --tailwind --ts --app --src-dir --eslint --import-alias "@/*" --turbopack --use-pnpm cd apps/web ``` The included flags set some opinionated defaults—such as Tailwind CSS, TypeScript, and eslint—so that you don't have to decide. You should now have your Sanity Studio and Next.js app in two separate, adjacent folders: ```text day-one/ └── apps/ ├── studio/ -> Sanity Studio └── web/ -> Next.js app ``` ### Sanity dependencies 1. **Run** the following command to install Sanity dependencies inside the `apps/web` directory ```sh # inside the apps/web directory pnpm install next-sanity ``` * [`next-sanity`](https://github.com/sanity-io/next-sanity) is a collection of utilities specifically tuned for Next.js when integrating with Sanity * [`@portabletext/react`](https://github.com/portabletext/react-portabletext#readme) (installed as part of `next-sanity`) is a React Component for rendering Portable Text with default components and the option to extend them for your own block content. This lesson has a deliberately narrow focus to query and render Sanity content in a front-end. For projects going into production, there are more factors to consider such as caching, revalidation, visual editing, SEO and more. As well as extra editing affordances such as "page building". 1. Consider taking the track of courses to explore in more detail. 2. The [`next-sanity` documentation](https://github.com/sanity-io/next-sanity?tab=readme-ov-file#next-sanity) contains more details for preparing Sanity and Next.js for production. 1. **Run** the following to start the development server for both your Studio and Next.js apps ```sh pnpm run dev ``` 1. Open [http://localhost:3000](http://localhost:3000) in your browser You should now see the default page for new Next.js applications, just like this: ![New Next.js home screen in development](https://cdn.sanity.io/images/3do82whm/next/56d754517b527b25156decb52ef90ec7ae76c1f8-2240x1480.png) ## Fetching Sanity content To fetch content from Sanity, you'll need a configured Sanity Client. In the code snippet below, you'll need to modify the `projectId` value to the one in your Studio's `sanity.config.ts` 1. **Create** a new file for the Sanity Client with your `projectId` ```typescript:apps/web/src/sanity/client.ts import { createClient } from "next-sanity"; export const client = createClient({ projectId: "REPLACE_WITH_YOUR_PROJECT_ID", dataset: "production", apiVersion: "2025-07-09", useCdn: false, }); ``` 1. In a production project, sharing values such as your Project ID across configuration files in a monorepo is better done with either a global environment variable or a `/packages` directory in your workspace. Sanity Client is a convenient way to interact with almost all of Sanity's APIs, such as fetching for content. In many frameworks, Sanity Client is all you'd use. In Next.js it's simple to do much better than a simple fetch. Instead of only making fetches as a page is requested, let's make the application ["Live by Default"](https://www.sanity.io/live) with a little extra configuration. 1. **Create** a new file to create live fetching utilities ```typescript:apps/web/src/sanity/live.ts import { defineLive } from "next-sanity/live"; import { client } from "@/sanity/client"; export const { sanityFetch, SanityLive } = defineLive({ client }); ``` 1. Next.js uses a "path alias" to import files from the `/src` directory using `@/` as shorthand. So you're importing `client` from `src/sanity/client.ts` in the example above. Not to be confused with the package `@sanity/client`! 1. **Update** the root layout to include the `SanityLive` component ```tsx:src/app/layout.tsx import { SanityLive } from "@/sanity/live"; import "./globals.css"; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( {children} ); } ``` ### Create the home page Next.js uses React Server Components, typically used as routes, for loading and displaying data. This home page is the root index route with the filename `page.tsx`. It's currently showing static content; let's replace that with content fetched from your Sanity project. Notice the GROQ query looking for all event-type documents that have a slug. 1. [Learn more about data fetching with Next.js and React Server Components](https://nextjs.org/learn/dashboard-app/fetching-data) 1. **Update** the home page route file ```tsx:apps/web/src/app/page.tsx import Link from "next/link"; import { defineQuery } from "next-sanity"; import { sanityFetch } from "@/sanity/live"; const EVENTS_QUERY = defineQuery(`*[ _type == "event" && defined(slug.current) && date > now() ]|order(date asc){_id, name, slug, date}`); export default async function IndexPage() { const { data: events } = await sanityFetch({ query: EVENTS_QUERY }); return (

Events

); } ``` Your home page should now look mostly the same but with published documents from your Studio. ![Listing of upcoming events on a web page](https://cdn.sanity.io/images/3do82whm/next/935ea38f3d0abade6983ced31d4549e8e6b7a42a-2240x1480.png) ### Create individual event pages Create another route to display each individual event. The query on this page will look for any event with a matching slug from the one used to load the page. 1. **Create** a route for individual event pages by adding a folder named `events` with another folder named `[slug]` within it 2. Create a new file in the `[slug]` folder named `page.tsx` ```tsx:src/app/events/[slug]/page.tsx import { defineQuery, PortableText } from "next-sanity"; import Link from "next/link"; import { notFound } from "next/navigation"; import { sanityFetch } from "@/sanity/live"; const EVENT_QUERY = defineQuery(`*[ _type == "event" && slug.current == $slug ][0]{ ..., "date": coalesce(date, now()), "doorsOpen": coalesce(doorsOpen, 0), headline->, venue-> }`); export default async function EventPage({ params, }: { params: Promise<{ slug: string }>; }) { const { data: event } = await sanityFetch({ query: EVENT_QUERY, params: await params, }); if (!event) { notFound(); } const { name, date, headline, details, eventType, doorsOpen, venue, tickets, } = event; const eventDate = new Date(date).toDateString(); const eventTime = new Date(date).toLocaleTimeString(); const doorsOpenTime = new Date( new Date(date).getTime() - doorsOpen * 60000 ).toLocaleTimeString(); const imageUrl = "https://placehold.co/550x310/png"; return (
← Back to events
{name
{eventType ? (
{eventType.replace("-", " ")}
) : null} {name ? (

{name}

) : null} {headline?.name ? (
Artist
{headline?.name}
) : null}
Date
{eventDate &&
{eventDate}
} {eventTime &&
{eventTime}
}
{doorsOpenTime ? (
Doors Open
Doors Open
{doorsOpenTime}
) : null} {venue?.name ? (
Venue
{venue.name}
) : null}
{details && details.length > 0 && (
)} {tickets && ( Buy Tickets )}
); } ``` A few things of note in the code example above: * The brackets in the `[slug]` folder name tell Next.js that it should make this part of the URL (`localhost:3000/events/**the-event-slug**`) dynamic, that is, available inside of the `params` property for the page template function. We can then use this information to query the correct document from Sanity (`$slug`). * Some deeply nested items use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) (`?.`) to only render an attribute if its parent exists. This is especially important when working with live preview where draft documents cannot be guaranteed to have values – even those you have required validation rules on. You should now be able to view the list of Events on the home page, click any one, and be shown its full details. ![A single event page](https://cdn.sanity.io/images/3do82whm/next/86d482a56ffc21254d056a1f4fda82de0af56798-2240x1480.png) Your app queries and renders text content, but the Content Lake stores assets such as media and images and Sanity's CDN includes image transformation to serve them in a performant way. Let's set this up in the next lesson.