2024.1.1 • Published 29 days ago

@shopify/hydrogen-react v2024.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
29 days ago

@shopify/hydrogen-react

IMPORTANT

This is an beta version of @shopify/hydrogen-react.

Refer to how this package is versioned.

This document contains the following topics:

Getting started

  • Run one of the following commands:

    npm:

    npm i --save @shopify/hydrogen-react

    Yarn:

    yarn add @shopify/hydrogen-react

Authenticating the Storefront client

To make it easier to query the Storefront API, Hydrogen UI exposes a helper function called createStorefrontClient().

The client can take in the following tokens:

  • Delegate access: Used for requests from a server or other private context. Set as privateStorefrontToken.

  • Public: Used for requests from a browser or other public context. Set as publicAccessToken.

The following is an example:

// Filename: '/shopify-client.js'

import {createStorefrontClient} from '@shopify/hydrogen-react';

const client = createStorefrontClient({
  privateStorefrontToken: '...',
  storeDomain: 'myshop',
  storefrontApiVersion: '2022-07',
});

export const getStorefrontApiUrl = client.getStorefrontApiUrl;
export const getPrivateTokenHeaders = client.getPrivateTokenHeaders;

You can then use this in your server-side queries. Here's an example of using it for NextJS's getServerSideProps:

// Filename: '/pages/index.js'

import {
  getStorefrontApiUrl,
  getPrivateTokenHeaders,
} from '../shopify-client.js';

export async function getServerSideProps() {
  const response = await fetch(getStorefrontApiUrl(), {
    body: GRAPHQL_QUERY,
    headers: getPrivateTokenHeaders({buyerIp: '...'}),
    method: 'POST',
  });

  const json = await response.json();

  return {props: json};
}

(Optional) Set the content type for the Storefront client

By default, the Storefront client sends the "content-type": "application/json" header. Use the json content type when you have GraphQL variables and when the body is an object with the following shape:

{
  "query": "...",
  "operationName": "...",
  "variables": { "myVariable": "someValue", ... }
}

However, when the body is only a query string, such as {"..."}, you can optionally change the default header to application/graphql:

createStorefrontClient({contentType: 'graphql', ...})

Alternatively, each time you get the headers you can customize which "content-type" you want, for only that one invocation:

getPrivateTokenHeaders({contentType: 'graphql'});

Note: If you're using TypeScript, then you can improve the typing experience.

Development and production bundles

Hydrogen UI has a development bundle and a production bundle. The development bundle has warnings and messages that the production bundle doesn't.

Depending on the bundler or runtime that you're using, the correct bundle might be automatically chosen following the package.json#exports of Hydrogen UI. If not, then you might need to configure your bundler / runtime to use the development and production conditions.

Note: The production bundle is used by default if your bundler / runtime doesn't understand the export conditions.

Hydrogen UI in the browser

Hydrogen UI has a development umd build and a production umd build. Both are meant to be used directly either by <script src=""></script> tags in HTML or by AMD-compatible loaders.

If you're using Hydrogen UI as a global through the <script> tag, then the components can be accessed through the hydrogenreact global variable.

Enable Storefront API GraphQL autocompletion

To improve your development experience, enable GraphQL autocompletion for the Storefront API in your integrated development environment (IDE).

  1. Add graphql and GraphQL-config with the following command:

    yarn add --dev graphql graphql-config
  2. Create a GraphQL config file at the root of your code. For example, .graphqlrc.yml.

  3. Add a schema and point it to Hydrogen UI's bundled schema for the Storefront API.

    For example:

    # Filename: .graphqlrc.yml
    schema: node_modules/@shopify/hydrogen-react/storefront.schema.json
  4. Install a GraphQL extension in your IDE, such as the GraphQL extension for VSCode.

GraphQL autocompletion and validation will now work in .graphql files and in gql template literals!

If you're having trouble getting it to work, then consult our troubleshooting section.

Set TypeScript types

Improve your development experience by adding strong typing to Storefront API responses. The following are some options for doing this.

Use the StorefrontApiResponseError and StorefrontApiResponseOk helpers

The following is an example:

import {
  type StorefrontApiResponseError,
  type StorefrontApiResponseOk,
} from '@shopify/hydrogen-react';

async function FetchApi<DataGeneric>() {
  const apiResponse = await fetch('...');

  if (!apiResponse.ok) {
    // 400 or 500 level error
    return (await apiResponse.text()) as StorefrontApiResponseError; // or apiResponse.json()
  }

  const graphqlResponse: StorefrontApiResponseOk<DataGeneric> =
    await apiResponse.json();

  // You can now access 'graphqlResponse.data' and 'graphqlResponse.errors'
}

Use the StorefrontApiResponse helper

If you're using a library that handles 400/500 level errors for you, then you can use StorefrontApiResponse. To add typing to objects that are trying to match a Storefront API object shape, you can import the shape.

The following is an example:

import type {Product} from '@shopify/hydrogen-react/storefront-api-types';

const product: Product = {};

Use TypeScript's helpers

To create your own object shapes, you can use TypeScript's built-in helpers.

The following is an example:

const partialProduct: Partial<Product> = {};

const productTitle: Pick<Product, 'title'> = '';

const productExceptTitle: Omit<Product, 'title'> = {};

Troubleshooting

The following will help you troubleshoot common problems in this version of Hydrogen UI.

GraphQL autocompletion

If you can't get GraphQL autocompletion to work, then try restarting the GraphQL server in your IDE.

For example, in VSCode do the following:

  1. Open the command palette.
  2. Type graphql.
  3. Select VSCode GraphQL: Manual Restart.
2024.1.1

2 months ago

2024.1.0

3 months ago

2023.10.1

5 months ago

2023.7.1

9 months ago

2023.7.0

9 months ago

2023.7.5

6 months ago

2023.7.4

8 months ago

2023.7.3

8 months ago

2023.7.2

9 months ago

2023.7.6

6 months ago

2023.10.0

6 months ago

2023.4.4

11 months ago

2023.4.3

12 months ago

2023.4.2

12 months ago

2023.4.1

12 months ago

2023.4.5

10 months ago

2023.4.0

1 year ago

2023.1.7

1 year ago

2023.1.8

1 year ago

2023.1.6

1 year ago

2023.1.5

1 year ago

2023.1.4

1 year ago

2022.10.6

1 year ago

2022.10.7

1 year ago

2022.10.8

1 year ago

2022.10.5

1 year ago

2022.10.4

1 year ago

2022.10.3

1 year ago

2022.10.2

1 year ago

2022.10.1

2 years ago

2022.10.0

2 years ago

2022.7.1

2 years ago

2022.7.0

2 years ago