GithubHelp home page GithubHelp logo

basementstudio / next-shopify Goto Github PK

View Code? Open in Web Editor NEW
30.0 2.0 3.0 1.08 MB

A context, a hook, and an API route handler, to manage a Shopify Storefront in your Next.js app.

License: MIT License

TypeScript 100.00%
typescript nextjs shopify storefront-api react-query e-commerce

next-shopify's Introduction

next-shopify

from the basement.

๐Ÿšจ Shopify is improving their APIs, and we are updating our integration. Don't use just yet.

Take a look at Shopify's Hydrogen.


A context, a hook, and an API route handler, to manage a Shopify Storefront in your Next.js app.

Install

yarn add next-shopify

Or with npm:

npm i next-shopify

Before You Start

In order to use the Storefront API, which is what this library uses, you'll need to set up your Shopify Store with a private app.

  1. Go to your private apps: https://<your-shopify-domain>/admin/apps/private, and create one.
  2. Down at the bottom of your app's dashboard, you'll need to enable the Storefront API and give it the correct permissions.
  3. Take hold of the Storefront Access Token โ€” we'll need it later.

Usage

Just three steps and we'll be ready to roll.

yarn add next-shopify

1. Wrap Your Application with the Context Provider

// pages/_app.tsx
import { AppProps } from 'next/app'
import { ShopifyContextProvider } from 'next-shopify'

const App = ({ Component, pageProps }: AppProps) => {
  return (
    <ShopifyContextProvider>
      <Component {...pageProps} />
    </ShopifyContextProvider>
  )
}

export default App

2. Add the API Route

We add an API Route, and we use next-shopify's built in handler.

// pages/api/shopify/[...storefront].ts
import { handleShopifyStorefront } from 'next-shopify'

// be sure to add the correct env variables.

export default handleShopifyStorefront({
  domain: process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN as string,
  storefrontAccessToken: process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN as string
})

3. Use the Hook

This is just an example.

import { useShopify } from 'next-shopify'

export const Cart = () => {
  const {
    cart,
    cartToggleState
    // cartItemsCount,
    // onAddLineItem,
    // onRemoveLineItem,
    // onUpdateLineItem
  } = useShopify()

  if (!cartToggleState.isOn || !cart) return null
  return (
    <div>
      <h2>Cart</h2>
      <button onClick={cartToggleState.handleOff}>Close</button>
      {cart.lineItems.map(lineItem => {
        return (
          <div key={lineItem.id}>
            <p>{lineItem.title}</p>
          </div>
        )
      })}
      <a href={cart.webUrl}>Checkout</a>
    </div>
  )
}

export const Header = () => {
  const { cartToggleState } = useShopify()

  return (
    <>
      <header>
        <a>Logo</a>
        <button onClick={cartToggleState.handleOn}>Open cart</button>
      </header>
      <Cart />
    </>
  )
}

Fetching Products

In the following example, we explain how to use some helper methods to fetch products. Be aware that shopify-buy typings are wrong, and thus our methods can receive a custom formatProduct function that can help you have a better TypeScript experience.

// lib/shopify.ts
import { createClient } from 'next-shopify'

const { fetchAllProducts, fetchProductByHandle, client } = createClient({
  domain: process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN as string,
  storefrontAccessToken: process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN as string
})

fetchAllProducts().then(products => {
  console.log(products)
})

fetchProductByHandle('<slug>').then(product => {
  console.log(product)
})

// Passing a formatter (for better TypeScript experience) --------

function formatProduct(p: ShopifyBuy.Product) {
  return {
    id: p.id.toString(),
    title: p.title,
    slug: (p as any).handle as string, // shopify buy typings are wrong, sorry for this...
    images: p.images.map(img => ({
      src: img.src,
      alt: (img as any).altText ?? null
    }))
  }
}

fetchAllProducts(formatProduct).then(products => {
  console.log(products)
})

fetchProductByHandle('<slug>', formatProduct).then(product => {
  console.log(product)
})

// We also expose the whole client -------------------------------

console.log(client)

Using Other shopify-buy Methods

shopify-buy is the official Storefront API JavaScript SDK. It's robust, but not easy to integrate โ€” precisely why we created next-shopify. Therefore, if you still need to use other shopify-buy methods, we expose the whole client like this:

// lib/shopify.ts
import { createClient } from 'next-shopify'

export const { client } = createClient({
  domain: process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN as string,
  storefrontAccessToken: process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN as string
})

we make cool sh*t that performs

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.