17 Commits

Author SHA1 Message Date
Malte Ubl
5304683150 Cache the cart content in VDC 2024-02-05 06:40:52 -08:00
Malte Ubl
0c3283f591 Upgrade to canary and fix static build 2024-02-04 16:57:55 -08:00
Malte Ubl
47a1c3eea1 next 14.1 2024-02-04 16:50:25 -08:00
Malte Ubl
d12fb77ef9 caching 2024-02-04 16:43:53 -08:00
Malte Ubl
59a00fe9ea Dont reco on 1 2024-02-03 09:58:59 -08:00
Malte Ubl
9c3cc1f8b6 Auto cart context 2024-02-03 09:56:08 -08:00
Alberto Benatti
3a18f9a098 Update next.js version to 14 inside README.md (#1243) 2023-11-15 08:48:11 -06:00
Benedikt Jónsson
2fe1527bea Use GitHub actions concurrency to cancel in progress workflows on PRs (#1232) 2023-11-10 13:46:08 -06:00
Lee Robinson
2448f5201c Upgrade to Next.js 14 (#1224) 2023-10-27 14:11:18 -05:00
Michele Riva
80e48001d9 docs: adds Orama integration into the readme file (#1221) 2023-10-26 21:17:58 -05:00
Lee Robinson
1f47796529 Improves form submissions and updates dependencies (#1209) 2023-10-10 21:45:55 -05:00
dependabot[bot]
ece49c4265 Bump styfle/cancel-workflow-action from 0.11.0 to 0.12.0 (#1217) 2023-10-10 21:31:00 -05:00
Tucker Massad
2035fa0431 Fixes pnpm typo in README (#1215) 2023-10-06 09:28:14 -05:00
Michael Novotny
5cb1245432 Adds environment variable validation (#1198)
* Adds environment variable validation

* Adds bracket checking in SHOPIFY_STORE_DOMAIN

* Prettier

* Adds link

---------

Co-authored-by: Lee Robinson <lrobinson2011@gmail.com>
2023-10-02 10:18:56 -05:00
Michael Novotny
d9f875b539 Removes unnecessary search state (#1201) 2023-09-18 15:25:03 -05:00
Netanel Gilad
b0f6e94fba Adds Wix provider (#1195) 2023-09-18 09:56:16 -05:00
dependabot[bot]
d8703e8140 Bump actions/checkout from 3 to 4 (#1188) 2023-09-04 11:41:34 -05:00
28 changed files with 1681 additions and 1118 deletions

View File

@@ -1,15 +1,18 @@
name: test
on: pull_request
# Cancel in progress workflows on pull_requests.
# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-a-fallback-value
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Cancel running workflows
uses: styfle/cancel-workflow-action@0.11.0
with:
access_token: ${{ github.token }}
- name: Checkout repo
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Set node version
uses: actions/setup-node@v3
with:
@@ -27,6 +30,6 @@ jobs:
key: node-modules-cache-${{ hashFiles('**/pnpm-lock.yaml') }}
- name: Install dependencies
if: steps.node-modules-cache.outputs.cache-hit != 'true'
run: pnpm install
run: pnpm install --no-frozen-lockfile
- name: Run tests
run: pnpm test

1
.gitignore vendored
View File

@@ -36,3 +36,4 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
.env*.local

View File

@@ -2,8 +2,8 @@
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": true,
"source.sortMembers": true
"source.fixAll": "explicit",
"source.organizeImports": "explicit",
"source.sortMembers": "explicit"
}
}

View File

@@ -2,7 +2,7 @@
# Next.js Commerce
A Next.js 13 and App Router-ready ecommerce template featuring:
A Next.js 14 and App Router-ready ecommerce template featuring:
- Next.js App Router
- Optimized for SEO using Next.js's Metadata
@@ -32,9 +32,18 @@ Vercel is happy to partner and work with any commerce provider to help them get
- [Shopware](https://github.com/shopwareLabs/vercel-commerce) ([Demo](https://shopware-vercel-commerce-react.vercel.app/))
- [Swell](https://github.com/swellstores/verswell-commerce) ([Demo](https://verswell-commerce.vercel.app/))
- [Umbraco](https://github.com/umbraco/Umbraco.VercelCommerce.Demo) ([Demo](https://vercel-commerce-demo.umbraco.com/))
- [Wix](https://github.com/wix/nextjs-commerce) ([Demo](https://wix-nextjs-commerce.vercel.app/))
> Note: Providers, if you are looking to use similar products for your demo, you can [download these assets](https://drive.google.com/file/d/1q_bKerjrwZgHwCw0ovfUMW6He9VtepO_/view?usp=sharing).
## Integrations
Integrations enable upgraded or additional functionality for Next.js Commerce
- [Orama](https://github.com/oramasearch/nextjs-commerce) ([Demo](https://vercel-commerce.oramasearch.com/))
- Upgrades search to include typeahead with dynamic re-rendering, vector-based similarity search, and JS-based configuration.
- Search runs entirely in the browser for smaller catalogs or on a CDN for larger.
## Running locally
You will need to use the environment variables [defined in `.env.example`](.env.example) to run Next.js Commerce. It's recommended you use [Vercel Environment Variables](https://vercel.com/docs/concepts/projects/environment-variables) for this, but a `.env` file is all that is necessary.
@@ -59,7 +68,7 @@ Your app should now be running on [localhost:3000](http://localhost:3000/).
1. Select the `Vercel Solutions` scope.
1. Connect to the existing `commerce-shopify` project.
1. Run `vc env pull` to get environment variables.
1. Run `pmpm dev` to ensure everything is working correctly.
1. Run `pnpm dev` to ensure everything is working correctly.
</details>
## Vercel, Next.js Commerce, and Shopify Integration Guide

View File

@@ -1,6 +1,6 @@
import Navbar from 'components/layout/navbar';
import { GeistSans } from 'geist/font';
import { ensureStartsWith } from 'lib/utils';
import { Inter } from 'next/font/google';
import { ReactNode, Suspense } from 'react';
import './globals.css';
@@ -31,17 +31,13 @@ export const metadata = {
})
};
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter'
});
export default async function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en" className={inter.variable}>
<html lang="en" className={GeistSans.variable}>
<body className="bg-neutral-50 text-black selection:bg-teal-300 dark:bg-neutral-900 dark:text-white dark:selection:bg-pink-500 dark:selection:text-white">
<Navbar />
<Suspense>
<Navbar />
</Suspense>
<Suspense>
<main>{children}</main>
</Suspense>

View File

@@ -3,6 +3,8 @@ import { ThreeItemGrid } from 'components/grid/three-items';
import Footer from 'components/layout/footer';
import { Suspense } from 'react';
export const runtime = 'edge';
export const metadata = {
description: 'High-performance ecommerce store built with Next.js, Vercel, and Shopify.',
openGraph: {

View File

@@ -1,4 +1,5 @@
import { getCollections, getPages, getProducts } from 'lib/shopify';
import { validateEnvironmentVariables } from 'lib/utils';
import { MetadataRoute } from 'next';
type Route = {
@@ -11,6 +12,8 @@ const baseUrl = process.env.NEXT_PUBLIC_VERCEL_URL
: 'http://localhost:3000';
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
validateEnvironmentVariables();
const routesMap = [''].map((route) => ({
url: `${baseUrl}${route}`,
lastModified: new Date().toISOString()

View File

@@ -1,9 +1,11 @@
'use server';
import { TAGS } from 'lib/constants';
import { addToCart, createCart, getCart, removeFromCart, updateCart } from 'lib/shopify';
import { revalidateTag } from 'next/cache';
import { cookies } from 'next/headers';
export const addItem = async (variantId: string | undefined): Promise<String | undefined> => {
export async function addItem(prevState: any, selectedVariantId: string | undefined) {
let cartId = cookies().get('cartId')?.value;
let cart;
@@ -17,45 +19,56 @@ export const addItem = async (variantId: string | undefined): Promise<String | u
cookies().set('cartId', cartId);
}
if (!variantId) {
if (!selectedVariantId) {
return 'Missing product variant ID';
}
try {
await addToCart(cartId, [{ merchandiseId: variantId, quantity: 1 }]);
await addToCart(cartId, [{ merchandiseId: selectedVariantId, quantity: 1 }]);
revalidateTag(TAGS.cart);
} catch (e) {
return 'Error adding item to cart';
}
};
}
export const removeItem = async (lineId: string): Promise<String | undefined> => {
export async function removeItem(prevState: any, lineId: string) {
const cartId = cookies().get('cartId')?.value;
if (!cartId) {
return 'Missing cart ID';
}
try {
await removeFromCart(cartId, [lineId]);
revalidateTag(TAGS.cart);
} catch (e) {
return 'Error removing item from cart';
}
};
}
export const updateItemQuantity = async ({
lineId,
variantId,
quantity
}: {
lineId: string;
variantId: string;
quantity: number;
}): Promise<String | undefined> => {
export async function updateItemQuantity(
prevState: any,
payload: {
lineId: string;
variantId: string;
quantity: number;
}
) {
const cartId = cookies().get('cartId')?.value;
if (!cartId) {
return 'Missing cart ID';
}
const { lineId, variantId, quantity } = payload;
try {
if (quantity === 0) {
await removeFromCart(cartId, [lineId]);
revalidateTag(TAGS.cart);
return;
}
await updateCart(cartId, [
{
id: lineId,
@@ -63,7 +76,8 @@ export const updateItemQuantity = async ({
quantity
}
]);
revalidateTag(TAGS.cart);
} catch (e) {
return 'Error updating item quantity';
}
};
}

View File

@@ -5,8 +5,63 @@ import clsx from 'clsx';
import { addItem } from 'components/cart/actions';
import LoadingDots from 'components/loading-dots';
import { ProductVariant } from 'lib/shopify/types';
import { useRouter, useSearchParams } from 'next/navigation';
import { useTransition } from 'react';
import { useSearchParams } from 'next/navigation';
import { useFormState, useFormStatus } from 'react-dom';
function SubmitButton({
availableForSale,
selectedVariantId
}: {
availableForSale: boolean;
selectedVariantId: string | undefined;
}) {
const { pending } = useFormStatus();
const buttonClasses =
'relative flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white';
const disabledClasses = 'cursor-not-allowed opacity-60 hover:opacity-60';
if (!availableForSale) {
return (
<button aria-disabled className={clsx(buttonClasses, disabledClasses)}>
Out Of Stock
</button>
);
}
if (!selectedVariantId) {
return (
<button
aria-label="Please select an option"
aria-disabled
className={clsx(buttonClasses, disabledClasses)}
>
<div className="absolute left-0 ml-4">
<PlusIcon className="h-5" />
</div>
Add To Cart
</button>
);
}
return (
<button
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
if (pending) e.preventDefault();
}}
aria-label="Add to cart"
aria-disabled={pending}
className={clsx(buttonClasses, {
'hover:opacity-90': true,
disabledClasses: pending
})}
>
<div className="absolute left-0 ml-4">
{pending ? <LoadingDots className="mb-3 bg-white" /> : <PlusIcon className="h-5" />}
</div>
Add To Cart
</button>
);
}
export function AddToCart({
variants,
@@ -15,9 +70,8 @@ export function AddToCart({
variants: ProductVariant[];
availableForSale: boolean;
}) {
const router = useRouter();
const [message, formAction] = useFormState(addItem, null);
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const defaultVariantId = variants.length === 1 ? variants[0]?.id : undefined;
const variant = variants.find((variant: ProductVariant) =>
variant.selectedOptions.every(
@@ -25,44 +79,14 @@ export function AddToCart({
)
);
const selectedVariantId = variant?.id || defaultVariantId;
const title = !availableForSale
? 'Out of stock'
: !selectedVariantId
? 'Please select options'
: undefined;
const actionWithVariant = formAction.bind(null, selectedVariantId);
return (
<button
aria-label="Add item to cart"
disabled={isPending || !availableForSale || !selectedVariantId}
title={title}
onClick={() => {
// Safeguard in case someone messes with `disabled` in devtools.
if (!availableForSale || !selectedVariantId) return;
startTransition(async () => {
const error = await addItem(selectedVariantId);
if (error) {
// Trigger the error boundary in the root error.js
throw new Error(error.toString());
}
router.refresh();
});
}}
className={clsx(
'relative flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white hover:opacity-90',
{
'cursor-not-allowed opacity-60 hover:opacity-60': !availableForSale || !selectedVariantId,
'cursor-not-allowed': isPending
}
)}
>
<div className="absolute left-0 ml-4">
{!isPending ? <PlusIcon className="h-5" /> : <LoadingDots className="mb-3 bg-white" />}
</div>
<span>{availableForSale ? 'Add To Cart' : 'Out Of Stock'}</span>
</button>
<form action={actionWithVariant}>
<SubmitButton availableForSale={availableForSale} selectedVariantId={selectedVariantId} />
<p aria-live="polite" className="sr-only" role="status">
{message}
</p>
</form>
);
}

View File

@@ -1,40 +1,31 @@
import { XMarkIcon } from '@heroicons/react/24/outline';
import LoadingDots from 'components/loading-dots';
import { useRouter } from 'next/navigation';
'use client';
import { XMarkIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
import { removeItem } from 'components/cart/actions';
import LoadingDots from 'components/loading-dots';
import type { CartItem } from 'lib/shopify/types';
import { useTransition } from 'react';
import { useFormState, useFormStatus } from 'react-dom';
export default function DeleteItemButton({ item }: { item: CartItem }) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button
aria-label="Remove cart item"
onClick={() => {
startTransition(async () => {
const error = await removeItem(item.id);
if (error) {
// Trigger the error boundary in the root error.js
throw new Error(error.toString());
}
router.refresh();
});
type="submit"
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
if (pending) e.preventDefault();
}}
disabled={isPending}
aria-label="Remove cart item"
aria-disabled={pending}
className={clsx(
'ease flex h-[17px] w-[17px] items-center justify-center rounded-full bg-neutral-500 transition-all duration-200',
{
'cursor-not-allowed px-0': isPending
'cursor-not-allowed px-0': pending
}
)}
>
{isPending ? (
{pending ? (
<LoadingDots className="bg-white" />
) : (
<XMarkIcon className="hover:text-accent-3 mx-[1px] h-4 w-4 text-white dark:text-black" />
@@ -42,3 +33,18 @@ export default function DeleteItemButton({ item }: { item: CartItem }) {
</button>
);
}
export function DeleteItemButton({ item }: { item: CartItem }) {
const [message, formAction] = useFormState(removeItem, null);
const itemId = item.id;
const actionWithVariant = formAction.bind(null, itemId);
return (
<form action={actionWithVariant}>
<SubmitButton />
<p aria-live="polite" className="sr-only" role="status">
{message}
</p>
</form>
);
}

View File

@@ -1,54 +1,32 @@
import { useRouter } from 'next/navigation';
import { useTransition } from 'react';
'use client';
import { MinusIcon, PlusIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
import { removeItem, updateItemQuantity } from 'components/cart/actions';
import { updateItemQuantity } from 'components/cart/actions';
import LoadingDots from 'components/loading-dots';
import type { CartItem } from 'lib/shopify/types';
import { useFormState, useFormStatus } from 'react-dom';
export default function EditItemQuantityButton({
item,
type
}: {
item: CartItem;
type: 'plus' | 'minus';
}) {
const router = useRouter();
const [isPending, startTransition] = useTransition();
function SubmitButton({ type }: { type: 'plus' | 'minus' }) {
const { pending } = useFormStatus();
return (
<button
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
onClick={() => {
startTransition(async () => {
const error =
type === 'minus' && item.quantity - 1 === 0
? await removeItem(item.id)
: await updateItemQuantity({
lineId: item.id,
variantId: item.merchandise.id,
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
});
if (error) {
// Trigger the error boundary in the root error.js
throw new Error(error.toString());
}
router.refresh();
});
type="submit"
onClick={(e: React.FormEvent<HTMLButtonElement>) => {
if (pending) e.preventDefault();
}}
disabled={isPending}
aria-label={type === 'plus' ? 'Increase item quantity' : 'Reduce item quantity'}
aria-disabled={pending}
className={clsx(
'ease flex h-full min-w-[36px] max-w-[36px] flex-none items-center justify-center rounded-full px-2 transition-all duration-200 hover:border-neutral-800 hover:opacity-80',
{
'cursor-not-allowed': isPending,
'cursor-not-allowed': pending,
'ml-auto': type === 'minus'
}
)}
>
{isPending ? (
{pending ? (
<LoadingDots className="bg-black dark:bg-white" />
) : type === 'plus' ? (
<PlusIcon className="h-4 w-4 dark:text-neutral-500" />
@@ -58,3 +36,22 @@ export default function EditItemQuantityButton({
</button>
);
}
export function EditItemQuantityButton({ item, type }: { item: CartItem; type: 'plus' | 'minus' }) {
const [message, formAction] = useFormState(updateItemQuantity, null);
const payload = {
lineId: item.id,
variantId: item.merchandise.id,
quantity: type === 'plus' ? item.quantity + 1 : item.quantity - 1
};
const actionWithVariant = formAction.bind(null, payload);
return (
<form action={actionWithVariant}>
<SubmitButton type={type} />
<p aria-live="polite" className="sr-only" role="status">
{message}
</p>
</form>
);
}

View File

@@ -10,8 +10,8 @@ import Image from 'next/image';
import Link from 'next/link';
import { Fragment, useEffect, useRef, useState } from 'react';
import CloseCart from './close-cart';
import DeleteItemButton from './delete-item-button';
import EditItemQuantityButton from './edit-item-quantity-button';
import { DeleteItemButton } from './delete-item-button';
import { EditItemQuantityButton } from './edit-item-quantity-button';
import OpenCart from './open-cart';
type MerchandiseSearchParams = {

View File

@@ -1,20 +0,0 @@
import { Suspense } from 'react';
//import { dynamic } from "next/render-mode"
import "server-only";
function D({ children }: { children: React.ReactNode }) {
//dynamic();
return children;
}
export function Dynamic({fallback, error, children}: {
fallback: React.ReactNode,
error: string,
children: React.ReactNode
}) {
return (
<Suspense fallback={fallback}>
<D>{children}</D>
</Suspense>
);
}

View File

@@ -58,9 +58,8 @@ export default async function Footer() {
<hr className="mx-4 hidden h-4 w-[1px] border-l border-neutral-400 md:inline-block" />
<p>Designed in California</p>
<p className="md:ml-auto">
Crafted by{' '}
<a href="https://vercel.com" className="text-black dark:text-white">
Vercel
Crafted by Vercel
</a>
</p>
</div>

View File

@@ -1,10 +1,10 @@
import Cart from 'components/cart';
import OpenCart from 'components/cart/open-cart';
import { Dynamic } from 'components/dynamic';
import LogoSquare from 'components/logo-square';
import { getMenu } from 'lib/shopify';
import { Menu } from 'lib/shopify/types';
import Link from 'next/link';
import { Suspense } from 'react';
import MobileMenu from './mobile-menu';
import Search from './search';
const { SITE_NAME } = process.env;
@@ -44,9 +44,9 @@ export default async function Navbar() {
<Search />
</div>
<div className="flex justify-end md:w-1/3">
<Dynamic fallback={<OpenCart />} error="There was an error opening the cart.">
<Suspense fallback={<OpenCart />}>
<Cart />
</Dynamic>
</Suspense>
</div>
</div>
</nav>

View File

@@ -1,19 +1,12 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { createUrl } from 'lib/utils';
import { useRouter, useSearchParams } from 'next/navigation';
export default function Search() {
const router = useRouter();
const searchParams = useSearchParams();
const [searchValue, setSearchValue] = useState('');
useEffect(() => {
setSearchValue(searchParams?.get('q') || '');
}, [searchParams, setSearchValue]);
function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
@@ -34,12 +27,12 @@ export default function Search() {
return (
<form onSubmit={onSubmit} className="w-max-[550px] relative w-full lg:w-80 xl:w-full">
<input
key={searchParams?.get('q')}
type="text"
name="search"
placeholder="Search for products..."
autoComplete="off"
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
defaultValue={searchParams?.get('q') || ''}
className="w-full rounded-lg border bg-white px-4 py-2 text-sm text-black placeholder:text-neutral-500 dark:border-neutral-800 dark:bg-transparent dark:text-white dark:placeholder:text-neutral-400"
/>
<div className="absolute right-0 top-0 mr-3 flex h-full items-center">

View File

@@ -19,7 +19,11 @@ export default function FilterList({ list, title }: { list: ListItem[]; title?:
return (
<>
<nav>
{title ? <h3 className="hidden text-xs text-neutral-500 md:block">{title}</h3> : null}
{title ? (
<h3 className="hidden text-xs text-neutral-500 dark:text-neutral-400 md:block">
{title}
</h3>
) : null}
<ul className="hidden md:block">
<FilterItemList list={list} />
</ul>

View File

@@ -1,4 +1,4 @@
import { ImageResponse } from 'next/server';
import { ImageResponse } from 'next/og';
import LogoIcon from './icons/logo';
export type Props = {

View File

@@ -1,6 +1,7 @@
import { AddToCart } from 'components/cart/add-to-cart';
import Price from 'components/price';
import Prose from 'components/prose';
import { FitToCart } from 'lib/ai/fit-to-cart';
import { Product } from 'lib/shopify/types';
import { VariantSelector } from './variant-selector';
@@ -24,8 +25,8 @@ export function ProductDescription({ product }: { product: Product }) {
html={product.descriptionHtml}
/>
) : null}
<AddToCart variants={product.variants} availableForSale={product.availableForSale} />
<FitToCart currentProduct={product} />
</>
);
}

84
lib/ai/fit-to-cart.tsx Normal file
View File

@@ -0,0 +1,84 @@
import { OpenAIStream, StreamingTextResponse } from 'ai';
import { getCart } from 'lib/shopify';
import { Product } from 'lib/shopify/types';
import { unstable_cache } from 'next/cache';
import { cookies } from 'next/headers';
import OpenAI from 'openai';
import { Suspense } from 'react';
async function getCartFromCookies() {
const cartId = cookies().get('cartId')?.value;
if (cartId) {
return getCart(cartId);
}
return null;
}
export async function FitToCart({ currentProduct }: { currentProduct: Product }) {
return (
<Suspense fallback={null}>
<FitToCartInternal currentProduct={currentProduct} />
</Suspense>
);
}
async function FitToCartInternal({ currentProduct }: { currentProduct: Product }) {
const pitch = await getPitch({ currentProduct });
if (!pitch) return null;
return <div className="mt-6 text-sm leading-tight dark:text-white/[60%]">{pitch}</div>;
}
const fireworks = new OpenAI({
baseURL: 'https://api.fireworks.ai/inference/v1',
apiKey: process.env.FIREWORKS_API_KEY!
});
function buildPrompt(prompt: string) {
return prompt.split('\n').map((message) => ({
role: 'user' as const,
content: message
}));
}
export async function getPitch({ currentProduct }: { currentProduct: Product }) {
const cart = await getCartFromCookies();
if (!cart) return null;
const products = cart.lines
.filter((line) => line.merchandise.product.id !== currentProduct.id)
.map((line) => `"${line.merchandise.product.title}"`);
if (!products.length) return null;
const prompt = `Write a 30 word pitch for why a person who has ${products.join(
' and '
)} in their shopping cart should also purchase the "${currentProduct.title}"`;
const query = {
model: 'accounts/fireworks/models/mistral-7b-instruct-4k',
stream: true,
messages: buildPrompt(prompt),
max_tokens: 1000,
temperature: 0.75,
top_p: 1,
frequency_penalty: 1
} as const;
return unstable_cache(async () => {
// Request the Fireworks API for the response based on the prompt
const response = await fireworks.chat.completions.create(query);
// Convert the response into a friendly text-stream
const stream = OpenAIStream(response);
// Respond with the stream
const streamingResponse = new StreamingTextResponse(stream);
let text = await streamingResponse.text();
// Remove the quotes from the response tht the LLM sometimes adds.
text = text.trim().replace(/^"/, '').replace(/"$/, '');
return text;
}, [
JSON.stringify(query),
'1.0',
process.env.VERCEL_BRANCH_URL || '',
process.env.NODE_ENV || ''
])();
}

View File

@@ -22,7 +22,8 @@ export const sorting: SortFilterItem[] = [
export const TAGS = {
collections: 'collections',
products: 'products'
products: 'products',
cart: 'cart'
};
export const HIDDEN_PRODUCT_TAG = 'nextjs-frontend-hidden';

View File

@@ -210,6 +210,10 @@ export async function createCart(): Promise<Cart> {
return reshapeCart(res.body.data.cartCreate.cart);
}
function revalidateCart(cartId: string) {
revalidateTag(`cart-${cartId}`);
}
export async function addToCart(
cartId: string,
lines: { merchandiseId: string; quantity: number }[]
@@ -222,6 +226,7 @@ export async function addToCart(
},
cache: 'no-store'
});
revalidateCart(cartId);
return reshapeCart(res.body.data.cartLinesAdd.cart);
}
@@ -234,6 +239,7 @@ export async function removeFromCart(cartId: string, lineIds: string[]): Promise
},
cache: 'no-store'
});
revalidateCart(cartId);
return reshapeCart(res.body.data.cartLinesRemove.cart);
}
@@ -250,6 +256,7 @@ export async function updateCart(
},
cache: 'no-store'
});
revalidateCart(cartId);
return reshapeCart(res.body.data.cartLinesUpdate.cart);
}
@@ -258,7 +265,7 @@ export async function getCart(cartId: string): Promise<Cart | undefined> {
const res = await shopifyFetch<ShopifyCartOperation>({
query: getCartQuery,
variables: { cartId },
cache: 'no-store'
tags: [TAGS.cart, `cart-${cartId}`]
});
// Old carts becomes `null` when you checkout.

View File

@@ -9,3 +9,31 @@ export const createUrl = (pathname: string, params: URLSearchParams | ReadonlyUR
export const ensureStartsWith = (stringToCheck: string, startsWith: string) =>
stringToCheck.startsWith(startsWith) ? stringToCheck : `${startsWith}${stringToCheck}`;
export const validateEnvironmentVariables = () => {
const requiredEnvironmentVariables = ['SHOPIFY_STORE_DOMAIN', 'SHOPIFY_STOREFRONT_ACCESS_TOKEN'];
const missingEnvironmentVariables = [] as string[];
requiredEnvironmentVariables.forEach((envVar) => {
if (!process.env[envVar]) {
missingEnvironmentVariables.push(envVar);
}
});
if (missingEnvironmentVariables.length) {
throw new Error(
`The following environment variables are missing. Your site will not work without them. Read more: https://vercel.com/docs/integrations/shopify#configure-environment-variables\n\n${missingEnvironmentVariables.join(
'\n'
)}\n`
);
}
if (
process.env.SHOPIFY_STORE_DOMAIN?.includes('[') ||
process.env.SHOPIFY_STORE_DOMAIN?.includes(']')
) {
throw new Error(
'Your `SHOPIFY_STORE_DOMAIN` environment variable includes brackets (ie. `[` and / or `]`). Your site will not work with them there. Please remove them.'
);
}
};

View File

@@ -4,9 +4,6 @@ module.exports = {
// Disabling on production builds because we're running checks on PRs via GitHub Actions.
ignoreDuringBuilds: true
},
experimental: {
serverActions: true
},
images: {
formats: ['image/avif', 'image/webp'],
remotePatterns: [

View File

@@ -22,31 +22,33 @@
"*": "prettier --write --ignore-unknown"
},
"dependencies": {
"@headlessui/react": "^1.7.15",
"@headlessui/react": "^1.7.17",
"@heroicons/react": "^2.0.18",
"ai": "^2.2.33",
"clsx": "^2.0.0",
"next": "13.4.13-canary.15",
"geist": "^1.0.0",
"next": "14.1.1-canary.27",
"openai": "^4.26.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"server-only": "^0.0.1"
"react-dom": "18.2.0"
},
"devDependencies": {
"@tailwindcss/container-queries": "^0.1.1",
"@tailwindcss/typography": "^0.5.9",
"@types/node": "20.4.4",
"@types/react": "18.2.16",
"@types/react-dom": "18.2.7",
"@tailwindcss/typography": "^0.5.10",
"@types/node": "20.8.9",
"@types/react": "18.2.33",
"@types/react-dom": "18.2.14",
"@vercel/git-hooks": "^1.0.0",
"autoprefixer": "^10.4.14",
"eslint": "^8.45.0",
"eslint-config-next": "^13.4.12",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-unicorn": "^48.0.0",
"lint-staged": "^13.2.3",
"postcss": "^8.4.27",
"prettier": "3.0.1",
"prettier-plugin-tailwindcss": "^0.4.1",
"tailwindcss": "^3.3.3",
"typescript": "5.1.6"
"autoprefixer": "^10.4.16",
"eslint": "^8.52.0",
"eslint-config-next": "^14.0.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-unicorn": "^48.0.1",
"lint-staged": "^15.0.2",
"postcss": "^8.4.31",
"prettier": "3.0.3",
"prettier-plugin-tailwindcss": "^0.5.6",
"tailwindcss": "^3.3.5",
"typescript": "5.2.2"
}
}

2247
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,9 @@
/** @type {import('prettier').Config} */
module.exports = {
singleQuote: true,
arrowParens: 'always',
trailingComma: 'none',
printWidth: 100,
tabWidth: 2,
// pnpm doesn't support plugin autoloading
// https://github.com/tailwindlabs/prettier-plugin-tailwindcss#installation
plugins: [require('prettier-plugin-tailwindcss')]
plugins: ['prettier-plugin-tailwindcss']
};

View File

@@ -6,7 +6,7 @@ module.exports = {
theme: {
extend: {
fontFamily: {
sans: ['var(--font-inter)']
sans: ['var(--font-geist-sans)']
},
keyframes: {
fadeIn: {