Skip to content

dwarfhq/sanity-shopify-hydrogen

Repository files navigation

AKVA - An example storefront powered by Sanity + Hydrogen

This demo is compatible with @shopify/hydrogen >= 2023.1.0 built on Remix.

For the legacy Hydrogen v1 template, please refer to the hydrogen-v1 branch.

Demo | Sanity Studio | Sanity Connect for Shopify

About

AKVA is our customized Hydrogen starter that presents a real-world example of how Sanity and Structured Content can elevate your custom Shopify storefronts.

It's designed to be used alongside our pre-configured Studio and Sanity Connect for Shopify, which syncs products and collections from your Shopify storefront to your Sanity dataset.

This starter showcases a few patterns you can adopt when creating your own custom storefronts. Use Sanity and Hydrogen to delight customers with rich, shoppable editorial experiences that best tell your story.

Features

View the feature gallery

This TypeScript demo adopts many of Hydrogen's framework conventions and third-party libraries. If you've used Hydrogen then you should hopefully feel at home here.

Fetching Sanity data

This demo comes preconfigured with a Sanity client that is available in the Remix context, enabling you to fetch content from Sanity in Remix loaders and actions.

In addition to this, we've created a query utility, which uses Hydrogen's caching strategies to reduce the number of calls to Sanity's API. If no straregy is provided to the cache option, then the Hydrogen CacheLong() strategy will be used by default.

It's possible to make calls to the Sanity API either with query:

import {json, type LoaderArgs} from '@shopify/remix-oxygen';
import type {SanityProductPage} from '~/lib/sanity';

const QUERY = `*[_type == 'product' && slug.current == $slug]`;

export async function loader({params, context}: LoaderArgs) {
  const cache = context.storefront.CacheLong();

  const sanityContent = await context.sanity.query<SanityProductPage>({
    query: QUERY,
    params: {
      slug: params.handle,
    },
    cache,
  });

  return json({sanityContent});
}

or directly with the Sanity client:

// <root>/app/routes/($lang).products.$handle.tsx
import {useLoaderData} from '@remix-run/react';
import {json, type LoaderArgs} from '@shopify/remix-oxygen';
import type {SanityProductPage} from '~/lib/sanity';

const QUERY = `*[_type == 'product' && slug.current == $slug]`;

export async function loader({params, context}: LoaderArgs) {
  const sanityContent = await context.sanity.client.fetch<SanityProductPage>(
    QUERY,
    {
      slug: params.handle,
    },
  );

  return json({sanityContent});
}
export default function Product() {
  const {sanityContent} = useLoaderData<typeof loader>();

  // ...
}

This uses our official @sanity/client library, so it supports all the methods you would expect to interact with Sanity API's

You can also use the defer and Await utilities from Remix to prioritize critical data:

// <root>/app/routes/($lang).products.$handle.tsx
import {Suspense} from 'react';
import {Await, useLoaderData} from '@remix-run/react';
import {defer, type LoaderArgs} from '@shopify/remix-oxygen';
import type {SanityProductPage, LessImportant} from '~/lib/sanity';

const QUERY = `*[_type == 'product' && slug.current == $slug]`;
const ANOTHER_QUERY = `*[references($id)]`;

export async function loader({params, context}: LoaderArgs) {
  /* Await the important content here */
  const sanityContent = await context.sanity.query<SanityProductPage>({
    query: QUERY,
    params: {
      slug: params.handle,
    },
  });

  /* This can wait - so don't await it - keep it as a promise */
  const moreSanityContent = context.sanity.query<LessImportant>({
    query: ANOTHER_QUERY,
    params: {
      id: sanityContent._id,
    },
  });

  return defer({sanityContent});
}
export default function Product() {
  const {sanityContent, moreSanityContent} = useLoaderData<typeof loader>();

  return (
    <div>
      <Content value={sanityContent} />
      {/* Wrap promises in a Suspense fallback and await them */}
      <Suspense fallback={<Spinner />}>
        <Await resolve={moreSanityContent}>
          {(content) => <MoreContent value={content} />}
        </Await>
      </Suspense>
    </div>
  );
}

Utilize Sanity's realtime content platform to give editors live-as-you-type previewing of their content. That way they can see, in context, how their changes will appear directly in the storefront.

Learn more about @sanity/preview-kit in the documentation

// <root>/app/routes/($lang)._index.tsx
export async function loader({context, params}: LoaderArgs) {
  // Fetch initial snapshot to render, in preview mode this will include a token in the request
  const page = await context.sanity.client.fetch<SanityHomePage>(QUERY);

  // ...rest of loader

  return json({
    page,
    // ...other loader data
  });
}

export default function Index() {
  const {page} = useLoaderData<typeof loader>();
  // In preview mode, use preview component
  const Component = usePreviewComponent<{page: SanityHomePage}>(Route, Preview);

  return <Component page={page} />;
}

function Route({page}: {page: SanityHomePage}) {
  return (
    <>
      {/* Page hero */}
      {page?.hero && <HomeHero hero={page.hero as SanityHeroHome} />}

      {page?.modules && (
        <div className={clsx('mb-32 mt-24 px-4', 'md:px-8')}>
          <ModuleGrid items={page.modules} />
        </div>
      )}
    </>
  );
}

function Preview(props: {page: SanityHomePage}) {
  const {usePreview} = usePreviewContext()!;
  // Query, resolving drafts, and listen for new changes
  const page = usePreview(HOME_PAGE_QUERY, undefined, props.page);

  return <Route page={page} />;
}

Opinions

We've taken the following opinions on how we've approached this demo.

Shopify is the source of truth for non-editorial content
  • For products, this includes titles, handles, variant images and product options.
  • For collections, this includes titles and collection images.
Shopify data stored in our Sanity dataset is used to improve the editor experience
  • This allows us to display things like product status, prices and even inventory levels right in our Sanity Studio.
  • Our application always fetches from Shopify's Storefront API at runtime to ensure we have the freshest data possible, especially important when dealing with fast-moving inventory.
Collections are managed entirely by Shopify
  • Shopify is used to handle collection rules and sort orders.
Product options are customized in Sanity
  • Data added to specific product options (for example, associating a hex value with the color 'Red', or a string value with the Poster size 'A2') is done in Sanity.
  • We treat this quite simply and manage these in a dedicated field within the Settings section of our studio. We also make sure to query this field whenever querying products in our Sanity dataset.
  • This could alternatively be managed with Shopify's metatags.
We don't surface Shopify HTML descriptions and metatags
  • For this demo, Shopify tags are used purely as a non-visual organizational tool (to drive automated collections) and we use Portable Text over Shopify's description HTML field. However, Hydrogen makes it very easy to surface these in your application if needed.
Non-product (regular) pages are managed entirely by Sanity
  • Shopify pages and blog posts (associated with the Online Store) channel aren't used in this demo. A dedicated page document type in Sanity has been created for this purpose.
We query our Sanity dataset when building sitemap.xml entries
  • We use Sanity as the source of truth when determining whether a product or collection page is visible.
  • This gives us the flexibility to add custom logic to control whether certain pages should be visible or not. For example, if you wanted to hide product pages within a specific date range, or hide collections that didn't have any editorial modules assigned to them.

Analytics

We've set up basic Shopify Analytics on this demo. The hasUserConsent boolean in <root>/app/root.tsx is set to true - you'll likely need to set up user consent based on the relevant regulations for your storefront.

Getting started

Requirements:

  • Node.js version 16.14.0 or higher
  • npm (or your package manager of choice, such as yarn or pnpm)

Getting Started

  1. Create a .env file, based on the .env.template file.

  2. Install dependencies and start the development server

    npm i
    npm run dev
  3. Visit the development environment running at http://localhost:3000.

For information on running production builds and deployment, see the Hydrogen documentation.

License

This repository is published under the MIT license.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published