Skip to content
Merged
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
42 changes: 42 additions & 0 deletions apps/shirt-shop-api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
.env*.local
5 changes: 5 additions & 0 deletions apps/shirt-shop-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# shirt-shop-api

This project serves as the backend for all Shirt Shop examples.

We use this separate backend as we don't want to force people cloning the template to set up a KV store.
145 changes: 145 additions & 0 deletions apps/shirt-shop-api/app/api/cart/[cartId]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { Redis } from '@upstash/redis';
import { NextResponse } from 'next/server';

interface CartItem {
id: string;
color: string;
size: string;
quantity: number;
}

interface Cart {
id: string;
items: CartItem[];
}

// Initialize Redis client
const redis = new Redis({
url: process.env.KV_REST_API_URL!,
token: process.env.KV_REST_API_TOKEN!,
});

// Helper function to get cart key
const getCartKey = (cartId: string) => `cart:${cartId}`;

// 22 hours in seconds
const CART_TTL = 22 * 60 * 60;

// GET /api/[cartId]
export async function GET(
request: Request,
{ params }: { params: Promise<{ cartId: string }> },
) {
const { cartId } = await params;
try {
const cartKey = getCartKey(cartId);
const cart = await redis.get<Cart>(cartKey);

if (!cart) {
const newCart: Cart = {
id: cartId,
items: [],
};
return NextResponse.json(newCart);
}

return NextResponse.json(cart);
} catch (error) {
console.error('Error fetching cart:', error);
return NextResponse.json(
{ error: 'Failed to fetch cart' },
{ status: 500 },
);
}
}

// POST /api/[cartId]
export async function POST(
request: Request,
{ params }: { params: Promise<{ cartId: string }> },
) {
const { cartId } = await params;
try {
const cartKey = getCartKey(cartId);
const item: CartItem = await request.json();

// Get existing cart or create new one
const existingCart = (await redis.get<Cart>(cartKey)) || {
id: cartId,
items: [],
};

// Find if item already exists
const existingItemIndex = existingCart.items.findIndex(
(i: CartItem) =>
i.id === item.id && i.color === item.color && i.size === item.size,
);

if (existingItemIndex >= 0) {
// Update quantity if item exists
existingCart.items[existingItemIndex].quantity += item.quantity;
} else {
// Add new item
existingCart.items.push(item);
}

// Save cart with expiration
await redis.set(cartKey, existingCart, { ex: CART_TTL });

return NextResponse.json(existingCart);
} catch (error) {
console.error('Error adding item to cart:', error);
return NextResponse.json(
{ error: 'Failed to add item to cart' },
{ status: 500 },
);
}
}

// DELETE /api/[cartId]
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ cartId: string }> },
) {
const { cartId } = await params;
try {
const cartKey = getCartKey(cartId);
const item = await request.json();

// Get existing cart
const existingCart = await redis.get<Cart>(cartKey);

if (!existingCart) {
return NextResponse.json({ error: 'Cart not found' }, { status: 404 });
}

// Find the index of the matching item
const itemIndex = existingCart.items.findIndex(
(i) => i.id === item.id && i.color === item.color && i.size === item.size,
);

if (itemIndex === -1) {
return NextResponse.json(
{ error: 'Item not found in cart' },
{ status: 404 },
);
}

if (existingCart.items[itemIndex].quantity === 1) {
existingCart.items.splice(itemIndex, 1);
} else {
existingCart.items[itemIndex].quantity -= 1;
}

// Save updated cart with expiration
await redis.set(cartKey, existingCart, { ex: CART_TTL });

return NextResponse.json(existingCart);
} catch (error) {
console.error('Error removing item from cart:', error);
return NextResponse.json(
{ error: 'Failed to remove item from cart' },
{ status: 500 },
);
}
}
Binary file added apps/shirt-shop-api/app/favicon.ico
Binary file not shown.
16 changes: 16 additions & 0 deletions apps/shirt-shop-api/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import { FlatCompat } from '@eslint/eslintrc';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const compat = new FlatCompat({
baseDirectory: __dirname,
});

const eslintConfig = [
...compat.extends('next/core-web-vitals', 'next/typescript'),
];

export default eslintConfig;
16 changes: 16 additions & 0 deletions apps/shirt-shop-api/next.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
/* config options here */
async redirects() {
return [
{
source: '/',
destination: 'https://flags-sdk.dev',
permanent: false,
},
];
},
};

export default nextConfig;
28 changes: 28 additions & 0 deletions apps/shirt-shop-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "shirt-shop-api",
"version": "0.1.0",
"private": true,
"scripts": {
"build": "next build",
"dev": "next dev --turbopack --port 3030",
"lint": "next lint",
"start": "next start"
},
"dependencies": {
"@upstash/redis": "1.34.4",
"next": "15.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.2.0",
"tailwindcss": "^4",
"typescript": "^5"
}
}
5 changes: 5 additions & 0 deletions apps/shirt-shop-api/postcss.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const config = {
plugins: ['@tailwindcss/postcss'],
};

export default config;
27 changes: 27 additions & 0 deletions apps/shirt-shop-api/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
30 changes: 30 additions & 0 deletions examples/shirt-shop/app/[code]/add-to-cart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use client';

import { track } from '@vercel/analytics';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { addToCart } from '@/lib/actions';
import { useProductDetailPageContext } from '@/components/utils/product-detail-page-context';
import { AddToCartButton } from '@/components/product-detail-page/add-to-cart-button';

export function AddToCart() {
const router = useRouter();
const { color, size } = useProductDetailPageContext();
const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
track('add_to_cart:viewed');
}, []);

return (
<AddToCartButton
isLoading={isLoading}
onClick={async () => {
setIsLoading(true);
track('add_to_cart:clicked');
await addToCart({ id: 'shirt', color, size, quantity: 1 });
router.push('/cart');
}}
/>
);
}
22 changes: 22 additions & 0 deletions examples/shirt-shop/app/[code]/cart/order-summary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { proceedToCheckoutColorFlag } from '@/flags';
import { OrderSummarySection } from '@/components/shopping-cart/order-summary-section';
import { ProceedToCheckout } from './proceed-to-checkout';

export async function OrderSummary({
showSummerBanner,
freeDelivery,
}: {
showSummerBanner: boolean;
freeDelivery: boolean;
}) {
// This is a fast feature flag so we don't suspend on it
const proceedToCheckoutColor = await proceedToCheckoutColorFlag();

return (
<OrderSummarySection
showSummerBanner={showSummerBanner}
freeDelivery={freeDelivery}
proceedToCheckout={<ProceedToCheckout color={proceedToCheckoutColor} />}
/>
);
}
33 changes: 33 additions & 0 deletions examples/shirt-shop/app/[code]/cart/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { OrderSummary } from '@/app/[code]/cart/order-summary';
import { Main } from '@/components/main';
import { ShoppingCart } from '@/components/shopping-cart/shopping-cart';
import {
productFlags,
showFreeDeliveryBannerFlag,
showSummerBannerFlag,
} from '@/flags';

export default async function CartPage({
params,
}: {
params: Promise<{ code: string }>;
}) {
const { code } = await params;
const showSummerBanner = await showSummerBannerFlag(code, productFlags);
const freeDeliveryBanner = await showFreeDeliveryBannerFlag(
code,
productFlags,
);

return (
<Main>
<div className="lg:grid lg:grid-cols-12 lg:items-start lg:gap-x-12 xl:gap-x-16">
<ShoppingCart />
<OrderSummary
showSummerBanner={showSummerBanner}
freeDelivery={freeDeliveryBanner}
/>
</div>
</Main>
);
}
Loading