In the world of modern web development, headless architecture has become a popular approach for building fast, efficient websites. It's a method that separates the content management system (CMS) from the presentation layer, allowing developers to use their preferred tools to create user interfaces while managing content independently through APIs.
This architecture offers several advantages, such as being framework agnostic, highly customizable, and optimized for SEO and performance. By decoupling the data from the visuals, the same content can be reused across various platforms and devices, providing a flexible solution for developers.
Understanding Key Tools: Sanity and Next.js
Sanity is an API-based headless CMS that provides developers with the ability to manipulate and retrieve content using APIs. It integrates seamlessly with React to render content into beautiful components. A standout feature of Sanity is its native preview functionality, which allows content editors to see changes before going live.
Next.js, on the other hand, is an excellent choice for the site builder. It's known for static site generation, server-side rendering, and dynamic routing. These features contribute to creating a super-fast application, as everything is compiled and bundled at build time, leading to enhanced performance.
The Role of Storybook in Development
Storybook is an interactive development environment that showcases components in isolation. This tool is beneficial for developers who want to prototype and test components without being in the app itself. It allows for quick iteration and exploration of component configurations, making it easier to build and maintain a component library.
By using Storybook, developers can view and interact with components like the Main Hero and Media Module. It provides a space for experimentation and verification of component behavior, leading to better-designed interfaces.
Setting Up the Project
To get started with building a website using Next.js and Sanity, the first step is setting up the project repository. Developers are encouraged to fork the repository to their GitHub account, clone it locally, and run the necessary scripts to get the development environment running.
During the setup, it's normal to encounter a 404 error, as the app and Sanity configuration are yet to be completed. At this stage, Storybook should be the only functional part, providing a preview of the components available for use in the project.
Creating the Sanity Interface
Building the authoring experience in Sanity involves defining a content model using schemas. These schemas act as blueprints for rendering the user interface in the CMS. Developers have the flexibility to customize the structure based on the project's needs.
In this context, content models typically fall into three categories: page content models, page modules, and data objects. Page content models define the metadata and layout for a page, while page modules mirror components. Data objects capture miscellaneous non-presentational data, such as SEO settings.
Defining Sanity Schemas
Sanity schemas are defined using a JSON-like structure, specifying the schema name, title, and a list of fields. The fields determine the inputs available in the CMS, such as text inputs or image selectors.
For example, a CTA banner schema might include fields for a heading, image, and call-to-action button. These fields mirror the props of a React component, ensuring consistency between the CMS and the front-end application.
Querying Content with GROQ
Sanity uses GROQ, its open-source query language, to fetch content. GROQ is similar to GraphQL but offers more flexibility in shaping the returned data. Developers can test GROQ queries within the Sanity studio using the Vision tab.
By crafting specific queries, developers can retrieve the exact data needed for their application, filtering and transforming it as required. This capability is crucial for efficiently building dynamic, content-driven websites.
Integrating Sanity with Next.js
To connect Sanity with Next.js, developers use the next-sanity library to create a client that fetches data from the CMS. This setup requires configuring environment variables in the project to establish a connection.
Next.js's file-based routing system allows developers to create dynamic routes for their application. By defining paths and fetching corresponding content from Sanity, developers can render pages based on the CMS data, creating a seamless integration.
Building Components Dynamically
Once the data is fetched, the next step is converting JSON data into React components. This is achieved using a build component function, which maps schema names to component names, ensuring the right components are rendered with the correct data.
Attention to detail is crucial here, as mismatched names can lead to rendering errors. By maintaining consistency in naming conventions, developers can ensure that components receive the appropriate content from Sanity.
Deploying to Production with Vercel
After building the application, the next step is deploying it to production. Vercel is a popular choice for hosting Next.js projects, providing seamless integration and monitoring tools.
To deploy, developers need to create a Vercel account, connect it to their GitHub repository, and configure environment variables. Setting up webhooks between Vercel and Sanity ensures that content updates trigger redeployment, keeping the live site in sync with the CMS.
Customizing and Expanding the Project
With the core setup complete, developers can customize their website by adjusting components, colors, and content. The flexibility of the headless architecture allows for easy expansion and modification as project requirements evolve.
By leveraging the capabilities of Next.js and Sanity, developers can build blazing fast, customizable websites that cater to the needs of modern web applications. This approach not only enhances performance but also simplifies content management, providing a powerful solution for developers working in today's digital landscape.
Join us for a hands-on workshop where we'll show you how to level up your React skills to build a high-performance headless website using Next.js, Sanity, and the JAMstack architecture. No prior knowledge of Next.js or Sanity is required, making this workshop ideal for anyone familiar with React who wants to learn more about building dynamic, responsive websites.
In this workshop, we'll explore how Next.js, a React-based framework, can be used to build a static website with server-side rendering and dynamic routing. You'll learn how to use Sanity as a headless CMS to manage your website’s content, create custom page templates with Next.js, use APIs to integrate with the CMS, and deploy your website to production with Vercel.
By the end of this workshop, you will have a solid understanding of how Next.js and Sanity.io can be used together to create a high-performance, scalable, and flexible website.
This workshop has been presented at React Summit 2023, check out the latest edition of this React Conference.
FAQ
Headless architecture refers to a setup where the front-end presentation layer is completely decoupled from the back-end content management system (CMS). The data is served to the site via an API, allowing developers to use any framework or technology for the front end while managing content separately in the CMS.
Using a headless CMS offers several benefits including being framework agnostic, which allows developers to use any front-end technology. It's highly customizable, supports SEO and performance optimizations, and the content can be reused across various digital platforms and devices efficiently.
To set up a repository for a Next.js and Sanity project, you typically fork and clone a starter repo, run 'npm install' to install dependencies, and use provided scripts to launch development environments for Storybook, the app, and Sanity.
Sanity is an API-based, headless CMS that allows for real-time editing and customization of content models. It supports a rich editor interface and provides a built-in preview functionality to see changes in real-time before publishing.
Next.js is a React framework used for building web applications. It supports features like static site generation, server-side rendering, and dynamic routing, which help in building fast and efficient web applications.
Deployment on Vercel for a Next.js application involves linking your GitHub repository with Vercel, setting up environment variables, and configuring webhooks to trigger rebuilds on content updates. Vercel automates the deployment process and provides a live URL for the hosted application.
Storybook is an open-source tool for developing UI components in isolation. It allows developers to build and test UI components interactively without needing to integrate them into a web app, making the development process faster and more efficient.
Data from Sanity can be queried in a Next.js project using Sanity's Grok query language. You can write queries to fetch specific data like page paths or content, which can then be used to dynamically generate pages or populate components in the application.
This workshop covers building blazing fast websites with Next.js and Sanity. It explores the benefits of headless architecture and CMS tools like Sanity. The workshop guides participants through setting up the repo, working with Sanity and Next.js, and deploying to production on Vercel. Content modeling in headless CMS and schema creation in Sanity are explained. The workshop also covers using Grok to query content, connecting content with Next.js, and deploying to production with Vercel.
This is Building Blazing Fast Websites with Next.js and Sanity. Natalia Iaffe, a software developer at RangleIO, specializes in front-end development and has experience with headless architecture and CMS like Sanity and Contentful. Nancy, an associate director of digital strategy at Rangle, is also a developer with expertise in headless CMS projects. The workshop will cover the platforms used, setting up the repo, working with Sanity and Next.js, and deploying to production on Vercel. The website being built is for a fictional organization called Pangea, focused on gardening.
2. Introduction to Headless Architecture and Tools
This website offers various services and provides all the tools to create a full app. Headless architecture separates the presentation layer from the content layer, allowing for framework agnostic development and customizability. Headless CMS tools are optimized for SEO and performance, and the decoupling of data and visuals enables content reuse across different channels. The CMS platform, like Sanity, manages content, while the site builder, like Next.js, combines content with React components to create a fast application. Sanity is an API-based headless CMS with a native preview functionality, and Next.js is great for static site generation and server-side rendering.
3. Next.js, Storybook, Repo Setup, and Sanity
Next.js and static site generation create fast apps. Vercel and Next.js work great together. Storybook is an interactive development environment for showcasing React components. Set up the repo by forking and cloning it, then run NPM install and the dev scripts. Sanity will be set up later. Thumbs up in Discord when ready. Nancy will guide through sanity setup. Storybook is running, but app and sanity need configuration. We'll be working with the media module today.
4. Setting Up Sanity Interface
In this section, we'll be setting up sanity, a customizable platform for creating interfaces. The desk structure with folders like pages and global is configured by the developer. The pages folder contains the pages and paths of our application. SanityHacka has a built-in preview feature for live updates. Components can be added and rearranged within sections. Sanity also provides an asset management system and a vision tab for querying data using the Grok querying language.
5. Understanding Content Modeling in Headless CMS
Before setting up our experiences, we need to understand content modeling in the headless CMS space. Content models define and model the interface using a schema. They act as blueprints for rendering content and can be used to model various types of data. The three types of content models are page content model, page module, and data object. The page content model mirrors the page structure, the page module mirrors components, and the data object stores non-presentational data.
6. Defining Content Models and Types
The page content model mirrors the information needed to create a page, including metadata and page layout. The page module mirrors a single component and its configuration. Sanity uses a specific syntax to create a schema for content models, which is a JSON object with specific fields. The schema includes a schema name, title, and a list of fields. Documents and object schemas are used to define page and page module content types. Documents are queryable, while objects are used to define custom field types. It's important to consider how the content will be queried when deciding whether to use a document or object type.
7. Field Types and Schema Creation in Sanity
The fields in Sanity are determined by the field type you enter, such as text inputs, toggles, or image selectors. Field validation and initial values can be configured to create a user-friendly interface. It's important to match the names of schemas and fields to component properties. Schema documentation provides a list of available types. The title property is used as a user-friendly label. Naming is case sensitive. Natalia will now provide a real example using the CTA banner component and guide through the schema creation process in Sanity.
8. Building the CTA Banner Schema
Let's dive into the codebase and see how we build a schema for the CTA banner component. The name and title of the schema match the component name. The schema's fields mirror the component's props, including heading, CTA, and image. The CTA field references another schema called CTA, which has boolean and string fields. These schemas and content models are the building blocks for the authoring experience in the sanity interface.
9. Schema Building and Content Querying
We've built the schema for the CTA banner component and added it to the sanity configuration. Now, let's explore how to query our content using Grok, Sanity's open-source query language. In the Sanity studio, we can test our Grok queries in the vision section and see the shape of the data. Grok is similar to GraphQL but offers even more flexibility and power. It allows us to query data to the shape we want.
10. Using Grok to Query Content
We'll be using Grok, Sanity's open-source query language, to query our content. Grok is similar to GraphQL but more flexible and powerful. We can test our Grok queries in the Sanity studio's vision section. By using square brackets, we can filter the documents we want to select, such as selecting all documents with the page type. Within the squiggly brackets, we can dictate the shape of the content we want to fetch back. We can also change the shape of the returned data, like simplifying the slug object to just return the URL. Additional filters can be added, and the dot, dot, dot notation returns all values inside the document. You can test the queries in the Vision section of Sanity studio.
11. Connecting Content with Next.js
We're going to connect the content created in Sanity to our Next.js repository. The code base primarily consists of the pages folder, which contains page layouts and routing. The folder and file structure determines the routing in Next.js. The app TSX file includes global elements like SEO, navigation, and footer, which are automatically rendered on every route. The utils folder contains the build component utility function, which converts JSON data from Sanity into React components. Next.js uses a file system-based router, where adding files and folders to the pages directory automatically creates routes. Dynamic routes are accomplished using square brackets and the file name. Catch-all segments and optional catch-all segments allow for more flexible routing.
12. Creating Dynamic Routes and Fetching Data
To create dynamic routes in Next.js, we use the Get Static Paths function to define a list of paths. We fetch the page path information from Sanity and map it to the expected structure. To query data from Sanity in Next.js, we use the next-sanity library's createClient function. This establishes a connection to the Sanity API. We fetch the page paths and content using the sanity client and the getStaticProps function in Next.js.
13. Fetching Data from Sanity with GetStaticProps
GetStaticProps fetches different data from Sanity, such as page, navigation, and footer data. The fetched data is returned as a global object, accessible in the underscore app file. All the fetched data is used to render the navigation and footer for each page. None of the data is hard coded.
14. Converting JSON to React Components
Now we need to convert the JSON data into React components using the build component function. The component mapper is created to match the schema name with the component name. If the data has the underscore type, the component is selected from the component map. The other properties in the JSON are used as props. In the Slug template, we map the path to the shape expected by Next.js. In the build component, we import the necessary modules into the components map. Finally, in the page component, we use the build component to generate React components for all the sections. Any questions? Let's get started!
15. Deploying to Production with Vercel
We map through the Sanity data, create a list of params object with our slugs. In build components, we import the components and plug them into the components map. In the page template, we map through the sections array and build components using the build component function. We deploy to production through Vercel by creating a new project, importing the GitHub repo, setting up environment variables, and creating a deploy hook in Vercel.
16. Completing Vercell and Sanity Connection
Just give any name to the trigger, copy the generated URL, go to Sanity's API section, paste the URL in the web hook section, select create, update, and delete triggers, and save. Once deployed, updates in Sanity will reflect on the live URL. Take some time to customize your website with images, color palettes, and text. We'll be available for 10 more minutes to answer questions and provide support. Thank you for joining us!
Knowledge of AI tooling is critical for future-proofing the careers of React developers, and the Vercel suite of AI tools is an approachable on-ramp. In this course, we’ll take a closer look at the Vercel AI SDK and how this can help React developers build streaming interfaces with JavaScript and Next.js. We’ll also incorporate additional 3rd party APIs to build and deploy a music visualization app. Topics:- Creating a React Project with Next.js- Choosing a LLM- Customizing Streaming Interfaces- Building Routes- Creating and Generating Components - Using Hooks (useChat, useCompletion, useActions, etc)
Frontend issues that affect your users are often triggered by backend problems. In this workshop, you’ll learn how to identify issues causing slow web pages and poor Core Web Vitals using tracing. Then, try it for yourself by setting up Sentry in a ready-made Next.js project to discover performance issues including slow database queries in an interactive pair-programming session. You’ll leave the workshop being able to:- Find backend issues that might be slowing down your frontend apps- Setup tracing with Sentry in a Next.js project- Debug and fix poor performance issues using tracing This will be a live 2-hour event where you’ll have the opportunity to code along with us and ask us questions.
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
In this workshop, first, we’ll go over the different ways you can consume APIs in React. Then, we’ll test each one by fetching content from a headless CMS (with both REST and GraphQL) and checking in detail how they work. While there is no advanced React knowledge required, this is going to be a hands-on session, so you’ll need to clone a preconfigured GitHub repository and utilize your preferred React programming editor, like VS Code. You will learn:- What diverse data fetching options there are in React- What are advantages and disadvantages of each- What are the typical use cases and when each strategy is more beneficial than others
If you’re like me, you probably have a million side-project ideas, some that could even make you money as a micro SaaS, or could turn out to be the next billion dollar startup. But how do you know which ones? How do you go from an idea into a functioning product that can be put into the hands of paying customers without quitting your job and sinking all of your time and investment into it? How can your solo side-projects compete with applications built by enormous teams and large enterprise companies? Building rich SaaS products comes with technical challenges like infrastructure, scaling, availability, security, and complicated subsystems like auth and payments. This is why it’s often the already established tech giants who can reasonably build and operate products like that. However, a new generation of devtools are enabling us developers to easily build complete solutions that take advantage of the best cloud infrastructure available, and offer an experience that allows you to rapidly iterate on your ideas for a low cost of $0. They take all the technical challenges of building and operating software products away from you so that you only have to spend your time building the features that your users want, giving you a reasonable chance to compete against the market by staying incredibly agile and responsive to the needs of users. In this 3 hour workshop you will start with a simple task management application built with React and Next.js and turn it into a scalable and fully functioning SaaS product by integrating a scalable database (PlanetScale), multi-tenant authentication (Clerk), and subscription based payments (Stripe). You will also learn how the principles of agile software development and domain driven design can help you build products quickly and cost-efficiently, and compete with existing solutions.
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.
React query version five is live and we'll be discussing the migration process to server components using Next.js and React Query. The process involves planning, preparing, and setting up server components, migrating pages, adding layouts, and moving components to the server. We'll also explore the benefits of server components such as reducing JavaScript shipping, enabling powerful caching, and leveraging the features of the app router. Additionally, we'll cover topics like handling authentication, rendering in server components, and the impact on server load and costs.
Today's Talk is about the Next.js App Router, which has evolved over the years and is now a core feature of Next.js. The Talk covers topics such as adding components, fetching remote data, and exploring layouts. It also discusses submitting form data, simplifying code, and reusing components. The App Router allows for coexistence with the existing pages router and enables data fetching at the layout level using React Server Components.
The Talk covers the speaker's personal journey into server-side rendering (SSR) and the evolution of web development frameworks. It explores the use of jQuery for animations in SSR, the challenges faced in integrating React with Umbraco, and the creation of a custom SSR framework. The Talk also discusses the benefits of Next.js and the use of serverless artifacts for deployment. Finally, it highlights the features of Astro, including its function per route capability.
This Talk explains how to handle URL slug changes in Next.js by using the getStaticPaths and getStaticProps methods. It covers implementing redirects and provides a solution to eliminate the need for editors to perform additional steps. The approach involves tracking URL slug changes and issuing proper redirects. The speaker encourages the audience to reach out with any questions or experiences with handling URL slugs.
This talk discusses the challenges and benefits of using Backend for Frontends (BFFs) and microservices in software development. It highlights how Next.js can simplify the creation of BFFs and unify the gateway for microservices. The talk also emphasizes the advantages of Next.js API routes in simplifying the development, deployment, and maintenance of APIs. It showcases the implementation of a BFF using Next.js and API routes, and the extension of API routes in an executable way. The speaker also mentions launching a course on using Next.js API routes for building a serverless GraphQL API.
Comments