Skip to main content

๐Ÿ“– Usage Guide

Once you've installed the SDK and initialized your client, you can start fetching Shopify data with full type safety and powerful customization options.

This guide shows you how to:

  • Fetch products or collections
  • Work with metafields
  • Handle server-side and client-side operations
  • Manage errors properly

๐Ÿง  Where should I use SDK functions?โ€‹

We recommend organizing your SDK calls inside a lib/NextShopKit/ folder.

Suggested structure:

lib/NextShopKit/client.ts        โ† SDK client setup
lib/NextShopKit/products.ts โ† getProduct, getCollection
lib/NextShopKit/cart.ts โ† Cart operations

You can also use the SDK directly where needed โ€” but for larger projects, centralizing logic improves maintainability.


โœ… Example: Fetch a Single Product with Error Handlingโ€‹

The getProduct() function returns an object with data and error. Always check for errors before accessing the result.

app/product/[handle]/page.tsx
import { getProduct } from "@/lib/NextShopKit/client";

export default async function ProductPage({ params }) {
const { data, error } = await getProduct({ handle: params.handle });

if (error || !data) {
// Handle your error logic here
return <div>Product not found.</div>;
}

return (
<div>
<h1>{data.title}</h1>
<p>
{data.price.amount} {data.price.currencyCode}
</p>
<div dangerouslySetInnerHTML={{ __html: data.descriptionHtml }} />
</div>
);
}

๐Ÿ“ฆ Example: Fetch Products by Collectionโ€‹

This example fetches products from a collection and handles metafields and formatting:

lib/NextShopKit/products.ts
import { getCollection } from "@/lib/NextShopKit/client";

export async function getCollectionProducts(slug: string) {
return await getCollection({
collectionHandle: slug,
customMetafields: [
{ field: "custom.brand", type: "single_line_text" },
{ field: "custom.weight", type: "decimal" },
{ field: "custom.short_description", type: "rich_text" },
],
options: {
renderRichTextAsHtml: true,
resolveFiles: true,
camelizeKeys: true,
transformMetafields: (raw, casted) => ({
...casted,
metaSummary: `Brand: ${casted["custom.brand"] || "N/A"} ยท ${
casted["custom.weight"] ? `${casted["custom.weight"]} kg` : ""
}`,
}),
},
});
}

You can customize this logic per use case or centralize it to reuse in many routes.

Transforming metafields with transformMetafields

You can use the transformMetafields option to reshape, simplify, or enhance the raw metafield data returned from Shopify.

This is especially useful when:

  • You want to flatten nested custom metafields into a more usable format
  • You need to restructure references (like Metaobject, File, or Product types)
  • You want to compute derived values, such as summaries or tags

In the example above, we're creating a new field metaSummary by combining two metafields:

  • custom.brand (as a string)
  • custom.weight (formatted in kilograms)

This helps you keep your rendering logic clean and centralized.


๐Ÿงช Pro Tip: "use server" in App Routerโ€‹

Since Next.js 13.4, you can add "use server" to your SDK-based utilities for guaranteed server-side execution.

app/actions/fetchProducts.ts
"use server";

import { getCollection } from "@/lib/NextShopKit/client";

export async function fetchProductsByCategory(category: string) {
return await getCollection({ collectionHandle: category });
}
info

This helps you reuse logic across components or pages while keeping sensitive tokens secure and improving performance.


๐Ÿ”’ Security & Usage Guidelinesโ€‹

Use private environment variables for optimal security and performance:

โœ… Best for:

  • Server Components (e.g., page.tsx)
  • API routes and Route Handlers
  • "use server" utilities
  • Static generation and SSR

โš›๏ธ Client-side Usage (When Required)โ€‹

Use NEXT_PUBLIC_ environment variables for interactive features:

โœ… Required for:

  • Cart management (CartProvider, useCart())
  • Real-time inventory updates
  • Interactive product configurators
  • Dynamic user-specific content
Security Best Practices
  • Server-side: Use private tokens, keep credentials secure
  • Client-side: Only use Storefront API tokens (never Admin API)
  • Permissions: Ensure minimal required permissions for client-side tokens
  • Monitoring: Consider rate limiting and request validation

๐Ÿ”— What's next?โ€‹

Now that you understand the basics, dive deeper into: