Next.js Commerce refresh. (#966)

We're making some updates to Next.js Commerce. Everything prior to this commit marks what we're calling [`v1`](https://github.com/vercel/commerce/releases/tag/v1) as a point in time to be able to reference and still use going into the future. The current architecture of Commerce is a multi-vendor, interoperable solution, including:

- [Shopify](https://shopify.vercel.store/)
- [Swell](https://swell.vercel.store/)
- [BigCommerce](https://bigcommerce.vercel.store/)
- [Vendure](https://vendure.vercel.store/)
- [Saleor](https://saleor.vercel.store/)
- [Ordercloud](https://ordercloud.vercel.store/)
- [Spree](https://spree.vercel.store/)
- [Kibo Commerce](https://kibocommerce.vercel.store/)
- [Commerce.js](https://commercejs.vercel.store/)
- [SalesForce Cloud Commerce](https://salesforce-cloud-commerce.vercel.store/)

All features can be toggled on or off, and it's easy to change between commerce providers. To support this, we needed to create a ["commerce metaframework"](d1d9e8c434/packages/commerce/new-provider.md) where providers could confirm to an API spec to add support for Next.js Commerce. While this worked and was successful for `v1`, we have different design goals and ambitions for `v2`.

**What You Need To Know**

- `v1` will not be updated moving forward. If you need to reference `v1`, you will still be able to clone and deploy the version tagged at this release.
- `v2` will be shifting to be a single provider vs. provider agnostic. Other providers are welcome to fork this repository and swap out the underlying `lib/` implementation that connects to the selected commerce provider (Shopify). This architecture was chosen to reduce the surface area of the codebase, remove the intermediate metaframework layer for provider-interoperability, and enable usage with the latest Next.js and React features.
- We will be sharing more about `v2` in the future as we continue to iterate before the marked release.
This commit is contained in:
Lee Robinson
2023-04-17 23:00:47 -04:00
committed by GitHub
parent d1d9e8c434
commit fd9450aecb
1288 changed files with 4997 additions and 148456 deletions

16
app/[page]/layout.tsx Normal file
View File

@@ -0,0 +1,16 @@
import Footer from 'components/layout/footer';
import { Suspense } from 'react';
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<Suspense>
<div className="w-full bg-white dark:bg-black">
<div className="mx-8 max-w-2xl py-20 sm:mx-auto">
<Suspense>{children}</Suspense>
</div>
</div>
{/* @ts-expect-error Server Component */}
<Footer />
</Suspense>
);
}

56
app/[page]/page.tsx Normal file
View File

@@ -0,0 +1,56 @@
import type { Metadata } from 'next';
import Prose from 'components/prose';
import { getPage } from 'lib/shopify';
import { notFound } from 'next/navigation';
export const runtime = 'edge';
export const revalidate = 43200; // 12 hours in seconds
export async function generateMetadata({
params
}: {
params: { page: string };
}): Promise<Metadata> {
const page = await getPage(params.page);
if (!page) return notFound();
return {
title: page.seo?.title || page.title,
description: page.seo?.description || page.bodySummary,
openGraph: {
images: [
{
url: `/api/og?title=${encodeURIComponent(page.title)}`,
width: 1200,
height: 630
}
],
publishedTime: page.createdAt,
modifiedTime: page.updatedAt,
type: 'article'
}
};
}
export default async function Page({ params }: { params: { page: string } }) {
const page = await getPage(params.page);
if (!page) return notFound();
return (
<>
<h1 className="mb-8 text-5xl font-bold">{page.title}</h1>
<Prose className="mb-8" html={page.body as string} />
<p className="text-sm italic">
{`This document was last updated on ${new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric'
}).format(new Date(page.updatedAt))}.`}
</p>
</>
);
}

75
app/api/cart/route.ts Normal file
View File

@@ -0,0 +1,75 @@
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { addToCart, removeFromCart, updateCart } from 'lib/shopify';
import { isShopifyError } from 'lib/type-guards';
function formatErrorMessage(err: Error): string {
return JSON.stringify(err, Object.getOwnPropertyNames(err));
}
export async function POST(req: NextRequest): Promise<Response> {
const cartId = cookies().get('cartId')?.value;
const { merchandiseId } = await req.json();
if (!cartId?.length || !merchandiseId?.length) {
return NextResponse.json({ error: 'Missing cartId or variantId' }, { status: 400 });
}
try {
await addToCart(cartId, [{ merchandiseId, quantity: 1 }]);
return NextResponse.json({ status: 204 });
} catch (e) {
if (isShopifyError(e)) {
return NextResponse.json({ message: formatErrorMessage(e.message) }, { status: e.status });
}
return NextResponse.json({ status: 500 });
}
}
export async function PUT(req: NextRequest): Promise<Response> {
const cartId = cookies().get('cartId')?.value;
const { variantId, quantity, lineId } = await req.json();
if (!cartId || !variantId || !quantity || !lineId) {
return NextResponse.json(
{ error: 'Missing cartId, variantId, lineId, or quantity' },
{ status: 400 }
);
}
try {
await updateCart(cartId, [
{
id: lineId,
merchandiseId: variantId,
quantity
}
]);
return NextResponse.json({ status: 204 });
} catch (e) {
if (isShopifyError(e)) {
return NextResponse.json({ message: formatErrorMessage(e.message) }, { status: e.status });
}
return NextResponse.json({ status: 500 });
}
}
export async function DELETE(req: NextRequest): Promise<Response> {
const cartId = cookies().get('cartId')?.value;
const { lineId } = await req.json();
if (!cartId || !lineId) {
return NextResponse.json({ error: 'Missing cartId or lineId' }, { status: 400 });
}
try {
await removeFromCart(cartId, [lineId]);
return NextResponse.json({ status: 204 });
} catch (e) {
if (isShopifyError(e)) {
return NextResponse.json({ message: formatErrorMessage(e.message) }, { status: e.status });
}
return NextResponse.json({ status: 500 });
}
}

BIN
app/api/og/Inter-Bold.ttf Normal file

Binary file not shown.

Binary file not shown.

66
app/api/og/route.tsx Normal file
View File

@@ -0,0 +1,66 @@
import { ImageResponse } from '@vercel/og';
import { SITE_NAME } from 'lib/constants';
import { NextRequest } from 'next/server';
export const runtime = 'edge';
const interRegular = fetch(new URL('./Inter-Regular.ttf', import.meta.url)).then((res) =>
res.arrayBuffer()
);
const interBold = fetch(new URL('./Inter-Bold.ttf', import.meta.url)).then((res) =>
res.arrayBuffer()
);
export async function GET(req: NextRequest): Promise<Response | ImageResponse> {
try {
const [regularFont, boldFont] = await Promise.all([interRegular, interBold]);
const { searchParams } = new URL(req.url);
const title = searchParams.has('title') ? searchParams.get('title')?.slice(0, 100) : SITE_NAME;
return new ImageResponse(
(
<div tw="flex h-full w-full flex-col items-center justify-center bg-black">
<svg viewBox="0 0 32 32" width="140">
<rect width="100%" height="100%" rx="16" fill="white" />
<path
fillRule="evenodd"
clipRule="evenodd"
fill="black"
d="M17.6482 10.1305L15.8785 7.02583L7.02979 22.5499H10.5278L17.6482 10.1305ZM19.8798 14.0457L18.11 17.1983L19.394 19.4511H16.8453L15.1056 22.5499H24.7272L19.8798 14.0457Z"
/>
</svg>
<div tw="mt-12 text-6xl text-white font-bold">{title}</div>
</div>
),
{
width: 1200,
height: 630,
fonts: [
{
name: 'Inter',
data: regularFont,
style: 'normal',
weight: 400
},
{
name: 'Inter',
data: boldFont,
style: 'normal',
weight: 700
}
]
}
);
} catch (e) {
if (!(e instanceof Error)) throw e;
console.log(e.message);
return new Response(`Failed to generate the image`, {
status: 500
});
}
}

10
app/error.tsx Normal file
View File

@@ -0,0 +1,10 @@
'use client';
export default function Error({ reset }: { reset: () => void }) {
return (
<div>
<h2>Something went wrong.</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}

BIN
app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 535 B

9
app/globals.css Normal file
View File

@@ -0,0 +1,9 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@supports (font: -apple-system-body) and (-webkit-appearance: none) {
img[loading='lazy'] {
clip-path: inset(0.6px);
}
}

42
app/layout.tsx Normal file
View File

@@ -0,0 +1,42 @@
import { Inter } from 'next/font/google';
import { ReactNode, Suspense } from 'react';
import './globals.css';
import Navbar from 'components/layout/navbar';
import { SITE_CREATOR, SITE_CREATOR_URL, SITE_NAME } from 'lib/constants';
export const metadata = {
title: {
default: SITE_NAME,
template: `%s | ${SITE_NAME}`
},
robots: {
follow: true,
index: true
},
twitter: {
card: 'summary_large_image',
creator: SITE_CREATOR,
site: SITE_CREATOR_URL
}
};
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}>
<body className="bg-white text-black selection:bg-teal-300 dark:bg-black dark:text-white dark:selection:bg-fuchsia-600 dark:selection:text-white">
{/* @ts-expect-error Server Component */}
<Navbar />
<Suspense>
<main>{children}</main>
</Suspense>
</body>
</html>
);
}

38
app/page.tsx Normal file
View File

@@ -0,0 +1,38 @@
import { Carousel } from 'components/carousel';
import { ThreeItemGrid } from 'components/grid/three-items';
import Footer from 'components/layout/footer';
import { SITE_NAME } from 'lib/constants';
import { Suspense } from 'react';
export const runtime = 'edge';
export const metadata = {
description: 'High-performance ecommerce store built with Next.js, Vercel, and Shopify.',
openGraph: {
images: [
{
url: `/api/og?title=${encodeURIComponent(SITE_NAME)}`,
width: 1200,
height: 630
}
],
type: 'website'
}
};
export default async function HomePage() {
return (
<>
{/* @ts-expect-error Server Component */}
<ThreeItemGrid />
<Suspense>
{/* @ts-expect-error Server Component */}
<Carousel />
<Suspense>
{/* @ts-expect-error Server Component */}
<Footer />
</Suspense>
</Suspense>
</>
);
}

View File

@@ -0,0 +1,130 @@
import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { Suspense } from 'react';
import Grid from 'components/grid';
import { GridTileImage } from 'components/grid/tile';
import Footer from 'components/layout/footer';
import { AddToCart } from 'components/product/add-to-cart';
import { Gallery } from 'components/product/gallery';
import { VariantSelector } from 'components/product/variant-selector';
import Prose from 'components/prose';
import { HIDDEN_PRODUCT_TAG } from 'lib/constants';
import { getProduct, getProductRecommendations } from 'lib/shopify';
import { Image } from 'lib/shopify/types';
export const runtime = 'edge';
export async function generateMetadata({
params
}: {
params: { handle: string };
}): Promise<Metadata> {
const product = await getProduct(params.handle);
if (!product) return notFound();
const { url, width, height, altText: alt } = product.featuredImage || {};
const hide = !product.tags.includes(HIDDEN_PRODUCT_TAG);
return {
title: product.seo.title || product.title,
description: product.seo.description || product.description,
robots: {
index: hide,
follow: hide,
googleBot: {
index: hide,
follow: hide
}
},
openGraph: url
? {
images: [
{
url,
width,
height,
alt
}
]
}
: null
};
}
export default async function ProductPage({ params }: { params: { handle: string } }) {
const product = await getProduct(params.handle);
if (!product) return notFound();
return (
<div>
<div className="lg:grid lg:grid-cols-6">
<div className="lg:col-span-4">
<Gallery
title={product.title}
amount={product.priceRange.maxVariantPrice.amount}
currencyCode={product.priceRange.maxVariantPrice.currencyCode}
images={product.images.map((image: Image) => ({
src: image.url,
altText: image.altText
}))}
/>
</div>
<div className="p-6 lg:col-span-2">
{/* @ts-expect-error Server Component */}
<VariantSelector options={product.options} variants={product.variants} />
{product.descriptionHtml ? (
<Prose className="mb-6 text-sm leading-tight" html={product.descriptionHtml} />
) : null}
<AddToCart variants={product.variants} availableForSale={product.availableForSale} />
</div>
</div>
<Suspense>
{/* @ts-expect-error Server Component */}
<RelatedProducts id={product.id} />
<Suspense>
{/* @ts-expect-error Server Component */}
<Footer />
</Suspense>
</Suspense>
</div>
);
}
async function RelatedProducts({ id }: { id: string }) {
const relatedProducts = await getProductRecommendations(id);
if (!relatedProducts) return null;
return (
<div className="px-4 py-8">
<div className="mb-4 text-3xl font-bold">Related Products</div>
<Grid className="grid-cols-2 lg:grid-cols-5">
{relatedProducts.map((product) => {
return (
<Grid.Item key={product.id} className="animate-fadeIn">
<Link
aria-label={product.title}
className="border-gay-300 group relative block aspect-square overflow-hidden border bg-gray-50"
href={`/product/${product.handle}`}
>
<GridTileImage
alt={product.title}
src={product.featuredImage.url}
width={600}
height={600}
/>
</Link>
</Grid.Item>
);
})}
</Grid>
</div>
);
}

View File

@@ -0,0 +1,46 @@
import { getCollection, getCollectionProducts } from 'lib/shopify';
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import SearchResults from 'components/layout/search/results';
export const runtime = 'edge';
export async function generateMetadata({
params
}: {
params: { collection: string };
}): Promise<Metadata> {
const collection = await getCollection(params.collection);
if (!collection) return notFound();
return {
title: collection.seo?.title || collection.title,
description:
collection.seo?.description || collection.description || `${collection.title} products`,
openGraph: {
images: [
{
url: `/api/og?title=${encodeURIComponent(collection.title)}`,
width: 1200,
height: 630
}
]
}
};
}
export default async function CategoryPage({ params }: { params: { collection: string } }) {
const products = await getCollectionProducts(params.collection);
return (
<section>
{/* @ts-expect-error Server Component */}
<SearchResults products={products} />
{products.length === 0 ? (
<p className="py-3 text-lg">{`No products found in this collection`}</p>
) : null}
</section>
);
}

23
app/search/layout.tsx Normal file
View File

@@ -0,0 +1,23 @@
import Footer from 'components/layout/footer';
import Collections from 'components/layout/search/collections';
import FilterList from 'components/layout/search/filter';
import { sorting } from 'lib/constants';
import { Suspense } from 'react';
export default function SearchLayout({ children }: { children: React.ReactNode }) {
return (
<Suspense>
<div className="mx-auto flex max-w-7xl flex-col bg-white py-6 text-black dark:bg-black dark:text-white md:flex-row">
<div className="order-first flex-none md:w-1/6">
<Collections />
</div>
<div className="order-last min-h-screen w-full md:order-none">{children}</div>
<div className="order-none md:order-last md:w-1/6 md:flex-none">
<FilterList list={sorting} title="Sort by" />
</div>
</div>
{/* @ts-expect-error Server Component */}
<Footer />
</Suspense>
);
}

13
app/search/loading.tsx Normal file
View File

@@ -0,0 +1,13 @@
import Grid from 'components/grid';
export default function Loading() {
return (
<Grid className="grid-cols-2 lg:grid-cols-3">
{Array(12)
.fill(0)
.map((_, index) => {
return <Grid.Item key={index} className="animate-pulse bg-gray-100 dark:bg-gray-900" />;
})}
</Grid>
);
}

41
app/search/page.tsx Normal file
View File

@@ -0,0 +1,41 @@
import SearchResults from 'components/layout/search/results';
import { defaultSort, sorting } from 'lib/constants';
import { getProducts } from 'lib/shopify';
export const runtime = 'edge';
export const metadata = {
title: 'Search',
description: 'Search for products in the store.'
};
export default async function SearchPage({
searchParams
}: {
searchParams?: { [key: string]: string | string[] | undefined };
}) {
const { sort, q: searchValue } = searchParams as { [key: string]: string };
const { sortKey, reverse } = sorting.find((item) => item.slug === sort) || defaultSort;
const products = await getProducts({ sortKey, reverse, query: searchValue });
const resultsText = products.length > 1 ? 'results' : 'result';
return (
<>
{searchValue &&
(products.length > 0 ? (
<p>
{`Showing ${products.length} ${resultsText} for `}
<span className="font-bold">&quot;{searchValue}&quot;</span>
</p>
) : (
<p>
{'There are no products that match '}
<span className="font-bold">&quot;{searchValue}&quot;</span>
</p>
))}
{/* @ts-expect-error Server Component */}
<SearchResults products={products} />
</>
);
}