Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Example]: RSC/SSR Cart with session #1833

Open
wants to merge 6 commits into
base: v1.x-2022-07
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions examples/cart-server-session/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# RSC/SSR Hydrogen Cart with session

A hydrogen example demonstrating a 💯 `.server-driven` basic Cart workflow.

- Provides a set of `cart` utilities (`getCart`, `createCart`...) as well as a GraphQL cart client
- Provides a `/api/cart/[action]` that handle POST requests from the different `get`, `create`, `add` and `remove` form actions.
- Persists `cartId` and `cartCount` to the session (cookie), so they can be used used during the `.server` lifecycle
- Uses form actions for all interactions with the API. e.g — AddToCart, remove..
- Provides `suspendedFn` a utility to enable `<Suspend />` friendly async API calls from `.server` components

### Additional context

[Oxygen Demo](https://hello-server-cart-596cadc157f9402f1570.o2.myshopify.dev/)

# Hydrogen

Hydrogen is a React framework and SDK that you can use to build fast and dynamic Shopify custom storefronts.

[Check out the docs](https://shopify.dev/custom-storefronts/hydrogen)

[Run this template on StackBlitz](https://stackblitz.com/github/Shopify/hydrogen/tree/stackblitz/templates/hello-world-js)

## Getting started

**Requirements:**

- Node.js version 16.5.0 or higher
- Yarn

```bash
npm init @shopify/hydrogen@latest --template hello-world-ts
```

Remember to update `hydrogen.config.js` with your shop's domain and Storefront API token!

## Building for production

```bash
yarn build
```

## Previewing a production build

To run a local preview of your Hydrogen app in an environment similar to Oxygen, build your Hydrogen app and then run `yarn preview`:

```bash
yarn build
yarn preview
```
23 changes: 23 additions & 0 deletions examples/cart-server-session/hydrogen.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {
defineConfig,
CookieSessionStorage,
PerformanceMetricsServerAnalyticsConnector,
} from '@shopify/hydrogen/config';

export default defineConfig({
shopify: () => ({
defaultLanguageCode: 'EN',
defaultCountryCode: 'GB',
storeDomain: 'hydrogen-preview.myshopify.com',
storefrontToken: '3b580e70970c4528da70c98e097c2fa0',
storefrontApiVersion: '2022-07',
}),
session: CookieSessionStorage('__session', {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
}),
serverAnalyticsConnectors: [PerformanceMetricsServerAnalyticsConnector],
});
16 changes: 16 additions & 0 deletions examples/cart-server-session/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="preconnect" href="https://cdn.shopify.com" />
<link rel="icon" type="image/svg+xml" href="/src/assets/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hydrogen App</title>
<link rel="stylesheet" href="/src/index.css" />
</head>

<body>
<div id="root"></div>
<script type="module" src="/@shopify/hydrogen/entry-client"></script>
</body>
</html>
12 changes: 12 additions & 0 deletions examples/cart-server-session/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"moduleResolution": "node16",
"lib": ["dom", "dom.iterable", "scripthost", "es2020"],
"jsx": "react",
"types": ["vite/client"]
},
"exclude": ["node_modules", "dist"],
"include": ["**/*.js", "**/*.jsx"]
}
23 changes: 23 additions & 0 deletions examples/cart-server-session/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "hello-cart-session",
"description": "A hydrogen example demonstrating a .server-driven basic Cart workflow.",
"version": "0.0.0",
"license": "MIT",
"private": true,
"scripts": {
"dev": "shopify hydrogen dev",
"build": "shopify hydrogen build",
"preview": "shopify hydrogen preview"
},
"devDependencies": {
"@shopify/cli": "latest",
"@shopify/cli-hydrogen": "latest",
"vite": "^2.9.0"
},
"dependencies": {
"@shopify/hydrogen": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"author": "juanp.prieto"
}
18 changes: 18 additions & 0 deletions examples/cart-server-session/public/assets/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
42 changes: 42 additions & 0 deletions examples/cart-server-session/src/App.server.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
ShopifyProvider,
Router,
FileRoutes,
CacheNone,
} from '@shopify/hydrogen';

import React from 'react';
import renderHydrogen from '@shopify/hydrogen/entry-server';
import {Suspense} from 'react';
import {Header} from '~/components/Header.server';
import {Sidebar} from '~/components/Sidebar.server';
import {AsyncGetCartLines} from '~/components/AsyncGetCartLines.server';

function App({request, response}) {
response.cache(CacheNone());
const isFavIconRequest = request.normalizedUrl.includes('favicon');

if (isFavIconRequest) {
return null;
}

const url = new URL(request.normalizedUrl);
const toggleSidebar = url.searchParams.get('toggleSidebar') || false;

return (
<ShopifyProvider>
<Header toggleSidebar={toggleSidebar}>
<Sidebar>
<Suspense fallback="Loading cart lines from API...">
<AsyncGetCartLines />
</Suspense>
</Sidebar>
</Header>
<Router>
<FileRoutes />
</Router>
</ShopifyProvider>
);
}

export default renderHydrogen(App);
49 changes: 49 additions & 0 deletions examples/cart-server-session/src/components/AddToCart.server.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {useSession} from '@shopify/hydrogen';

export function AddToCart({id, variant}) {
const {cartId} = useSession();
return (
<form
id={id}
method="POST"
style={{display: 'flex', flexDirection: 'column'}}
>
{/* hidden info fields needed by the cart api */}
<input hidden type="text" name="cartId" defaultValue={cartId} />
<input
hidden
type="checkbox"
readOnly
name="toggleSidebar"
checked={true}
/>
<input
hidden
type="text"
name="merchandiseId"
defaultValue={btoa(variant.id)}
/>

<div style={{display: 'flex', gap: '0rem 1.5rem'}}>
{/*
if no cart is available, we create it with the line item,
else we update it with the new item
*/}
<button
type="submit"
formAction={cartId ? '/api/cart/linesAdd' : '/api/cart/create'}
disabled={!variant.availableForSale}
>
Add To Cart
</button>

<input
type="number"
name="quantity"
defaultValue={1}
style={{width: '40px'}}
/>
</div>
</form>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {useSession} from '@shopify/hydrogen';
import {getCart} from '~/utils/cart';
import {suspendedFn} from '~/utils/suspendedFn';
import {CartLines} from '~/components/CartLines.server';

// Create a .server <Suspense /> friendly version of an async function.
const getCartLinesSync = suspendedFn(getCart);

export function AsyncGetCartLines() {
const {cartId} = useSession();
const cart = cartId ? getCartLinesSync({id: cartId}) : [];

return <CartLines lines={cart?.lines ?? []} />;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {useSession} from '@shopify/hydrogen';

export function CartCount() {
const {cartCount} = useSession();

return <p>CART ({cartCount || 0})</p>;
}
74 changes: 74 additions & 0 deletions examples/cart-server-session/src/components/CartLines.server.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {useSession, flattenConnection} from '@shopify/hydrogen';

export function CartLines({lines = []}) {
return (
<div>
<hr />
<div
style={{
padding: '.5rem 1rem',
height: 'calc(100vh - 100px)',
overflowY: 'scroll',
}}
>
{/* each line items */}
{lines?.length ? (
(lines || []).map((line) => {
return <CartLine key={line.id} {...line} />;
})
) : (
<p>No items in cart</p>
)}
</div>
</div>
);
}

function CartLine({id, merchandise, quantity}) {
const [image] = flattenConnection(merchandise.product.images);
const {cartId} = useSession();
return (
<div key={id}>
{image?.thumb ? <img src={image.thumb} width={100} /> : null}
<p style={{marginTop: 0, marginBottom: 0}}>{merchandise.product.title}</p>
<small>{merchandise.title}</small>

<form method="POST">
{/* hidden info fields needed by the cart api */}
<input hidden name="cartId" defaultValue={cartId} />
<input
hidden
type="checkbox"
name="toggleSidebar"
checked={false}
readOnly
/>
<input
type="text"
hidden
name="lineIds"
defaultValue={JSON.stringify([id])}
/>

<div
style={{
marginBottom: '1rem',
paddingBottom: '1rem',
display: 'flex',
borderBottom: '1px solid white',
}}
>
<input
type="number"
name="quantity"
defaultValue={quantity}
style={{width: '40px'}}
/>
<button type="submit" formAction="/api/cart/linesRemove">
Remove
</button>
</div>
</form>
</div>
);
}
27 changes: 27 additions & 0 deletions examples/cart-server-session/src/components/Header.server.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {SidebarToggle} from '~/components/SidebarToggle.server';
import {CartCount} from '~/components/CartCount.server';

export function Header({children, toggleSidebar}) {
return (
<header>
<div
id="header__container"
style={{
display: 'flex',
gap: '1rem',
alignItems: 'center',
}}
>
<SidebarToggle open={toggleSidebar} />

<strong>Cart Session + Server Demo</strong>

<CartCount />

{/* Sidebar will render here */}
{children}
</div>
<hr />
</header>
);
}
12 changes: 12 additions & 0 deletions examples/cart-server-session/src/components/ProductItem.server.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {AddToCart} from '~/components/AddToCart.server';

export function ProductItem({id, title, image, variant}) {
return (
<div>
<img src={image} width={100} />
<p style={{marginBottom: '.25rem'}}>{title}</p>

<AddToCart id={id} variant={variant} />
</div>
);
}
Loading