Building the frontend of an e-commerce website is often the enjoyable part of the project.
With Next.js, React, and Tailwind CSS, you can create beautiful product pages, responsive layouts, custom shopping carts, and personalized shopping experiences.
But once you start implementing the actual commerce functionality, things become more complicated.
You need to think about:
- Database schemas for products and categories.
- Inventory management.
- Product variants.
- Shopping cart persistence.
- Payment gateway integrations.
- Payment verification and webhooks.
- Order management.
- Customer notifications.
- Administrative dashboards.
- Security and API authentication.
Building and maintaining all these systems can become a separate project on its own.
But what if you could build the entire customer-facing storefront in Next.js while connecting it to an existing ecommerce backend?
That is exactly what we're going to do in this tutorial.
We'll use Shoprivet as our headless commerce backend and build a custom online fashion store using Next.js, TypeScript, and Tailwind CSS.
No Shopify. No custom database. No Express or NestJS server. No visual storefront builder.
Just your own React components connected to a managed e-commerce API.
What We're Going to Build
We'll create a fashion storefront called Atelier Noir, a minimalist clothing brand with a contemporary visual identity.
Our application will include:
- A responsive navigation bar.
- An editorial-style hero section.
- A dynamic product catalog.
- Product photography and pricing.
- Product search.
- Add-to-cart functionality.
- A persistent guest shopping cart.
- Quantity management.
- Customer checkout.
- Available payment methods.
- Order confirmation.
- A separate merchant dashboard.
All the storefront components will be written in React.
Products, inventory, carts, and orders will be managed through Shoprivet.
<!-- Add a screenshot of the completed Next.js storefront here after running the application. -->
By the end of this tutorial, you'll understand how to use an ecommerce REST API to build a custom online store without developing an entire commerce backend yourself.
What Is Headless Ecommerce?
Traditional ecommerce platforms often combine the storefront, administrative dashboard, product database, and checkout system into a single application.
Headless ecommerce separates the customer-facing website from the underlying commerce infrastructure.
The frontend can be built using any framework you prefer, while the commerce backend exposes functionality through APIs.
For example:
- Next.js handles the storefront.
- React handles customer interactions.
- Tailwind CSS handles the appearance.
- Shoprivet handles commerce data and operations.
- Connected payment providers process online payments.
This allows developers to build shopping experiences without being restricted to a particular website builder or storefront template.
What Is Shoprivet?
Shoprivet is an ecommerce platform that provides several ways to build and operate online stores.

You can use Shoprivet to:
- Build a hosted online store.
- Embed a product catalog into an existing website.
- Build a completely custom storefront using its REST API.
For this tutorial, we're interested in the third option.
We won't use the storefront builder or embed an existing catalog widget.
Instead, we'll use Shoprivet as the commerce infrastructure behind our Next.js application.
The platform provides a dashboard where merchants can manage products, stock, categories, discounts, payment configurations, and customer orders.
Developers can interact with the underlying commerce functionality through documented API endpoints.
How Our Next.js Ecommerce Architecture Works
Our application will have two main layers.
CUSTOM NEXT.JS STOREFRONT
│
├── Homepage
├── Product catalog
├── Product search
├── Shopping cart
├── Checkout
└── Order confirmation
│
│ HTTPS requests
▼
SHOPRIVET COMMERCE API
│
├── Products
├── Categories
├── Inventory
├── Guest carts
├── Checkout
├── Payment integrations
└── Orders
│
▼
CONNECTED PAYMENT PROVIDERS
Instead of creating our own database tables for products, inventory, carts, and orders, we'll use the functionality provided by Shoprivet.
We will still use Next.js server-side rendering to securely retrieve product data using a merchant API key.
However, we won't need a separate backend application, database server, ORM, or custom implementation of the core ecommerce operations.
Understanding Shoprivet's Two APIs
Before writing any code, it's important to understand the difference between Shoprivet's management API and public storefront API.
The Management API
The management API uses versioned endpoints under /v1.
It allows authorized developers to perform operations such as:
- Creating and managing stores.
- Creating and updating products.
- Managing categories.
- Retrieving customer orders.
- Updating order statuses.
An example request looks like this:
GET /v1/stores/STORE_ID/products
Authorization: Bearer YOUR_API_KEY
These endpoints require a private merchant API key.
The key must never be exposed to customers or included in your browser's JavaScript bundle.
The Public Storefront API
The public storefront API provides customer-facing commerce functionality.
It can be used to:
- Retrieve public store information.
- Display available products.
- Retrieve available payment methods.
- Create guest shopping carts.
- Add and remove cart items.
- Initiate checkout.
- Retrieve authorized customer orders.
- Confirm online payments.
For example:
GET /public/stores/STORE_SLUG/products
Public storefront endpoints do not require a merchant API key.
Guest cart and protected order operations instead use their own scoped credentials.
| Feature | Management API | Public storefront API | |---|---|---| | Authentication | Merchant API key | Guest cart or order credential where required | | Product management | Yes | No | | Public product browsing | Possible through filtered server-side data | Yes | | Guest shopping carts | Not its primary purpose | Yes | | Customer checkout | Not its primary purpose | Yes | | Merchant order management | Yes | No | | Suitable for browser requests | No | Yes |
We'll use both APIs throughout this tutorial.
Step 1: Create a Free Shoprivet Account
Visit shoprivet.io to get started.

Click the signup button or navigate directly to the registration page.
Create an account using your name, email address, and password, then complete the verification process.

Once you're signed in, you'll be able to create and manage your own commerce store.
You can start with the free plan and explore the available functionality before deciding whether your business requires a paid subscription.
Step 2: Create Your Ecommerce Store
From your Shoprivet dashboard, create a new blank store.
We don't need to select a storefront template because we're going to build the frontend ourselves.
Enter Your Store Information
For this tutorial, we'll use the following example:
- Store name: Atelier Noir
- Description: Contemporary essentials for everyday living.
- Product type: Physical products
- Currency: USD

Select Your Product Type
Shoprivet supports stores selling physical or digital products.
Since we're building a clothing store, select physical products.

Choose Your Currency
Select the currency in which your products will be priced.

Complete the store creation process.
We now have a commerce dashboard that will serve as the administrative interface for our custom Next.js application.
The screenshots throughout the setup process may show products or store names from existing demonstration stores.
Step 3: Add Products to Your Store
Before building our frontend, we need something to display.
Navigate to Products in the dashboard.

Create a few products for the fashion collection.
Here are some example products you can use:
| Product | Price | Category | |---|---:|---| | Essential Cotton Tee | $35 | Essentials | | Relaxed Linen Shirt | $69 | Shirts | | Structured Blazer | $129 | Outerwear | | Everyday Trousers | $79 | Trousers | | Minimalist Canvas Tote | $29 | Accessories | | Classic Knit Sweater | $89 | Knitwear |
For each product, provide:
- A product name.
- A description.
- A selling price.
- Product photographs.
- Stock information, if applicable.
- A product category.

Use high-quality images with consistent lighting and aspect ratios if you want your storefront to have a professional appearance.
Once the products are ready, ensure they are published.

Our first implementation will use products without variants.
Shoprivet also supports product options and variants, including different sizes, colors, images, prices, stock quantities, and SKUs on eligible Premium and Business plans.
We'll discuss extending the application to support variants later.
Step 4: Generate Your Shoprivet API Key
This is where our tutorial becomes different from the typical visual ecommerce setup.
Look at the left sidebar of your Shoprivet dashboard.
Under the Manage section, select Developers.
You can also navigate to the Developers dashboard after signing in.

The Developers page contains everything you need to start integrating Shoprivet into your own applications.
You'll find:
- API key management.
- Configurable API rate limiting.
- JavaScript and cURL examples.
- Your store ID.
- Management API endpoints.
- Public storefront API endpoints.
- Example request bodies.
- Example API responses.
- Shopping cart and checkout documentation.
Create an API Key
In the API keys section:
- Enter a descriptive key name, such as
Atelier Noir Next.js Store. - Click Create API key.
- Copy the generated key immediately.
- Store it securely.
The full API key is displayed only once.
If you lose it, generate a replacement through the dashboard.
<!-- Optional: Add a screenshot of the newly generated API key dialog with the secret completely redacted. -->
Copy Your Store ID
Scroll down to the Use the API section.
Locate the field labeled Your store ID and click Copy ID.
We'll use this identifier when making requests to the authenticated management API.
You'll also need your store slug for the public storefront API.
The store slug appears in the public storefront examples in the Developers section.
For this tutorial, our example slug is:
atelier-noir
Use the actual slug assigned to your store.
Understand API Rate Limiting
The Developers dashboard also allows you to configure the number of authenticated API requests permitted per minute.
The documented default is 60 requests per minute, with a configurable range of 10 to 300.
Each API key has its own rate-limit window.
Requests exceeding the configured limit return HTTP status 429, together with rate-limit information.
We'll cache our catalog requests in Next.js to avoid making unnecessary requests every time someone visits the website.
Step 5: Create Your Next.js Project
Open your terminal and create a new Next.js application.
npx create-next-app@latest atelier-noir \
--typescript \
--tailwind \
--eslint \
--app \
--src-dir \
--use-npm \
--import-alias "@/*"
Navigate into the application.
cd atelier-noir
Install a few additional dependencies.
npm install lucide-react server-only
We'll use:
- Next.js App Router for the application structure.
- TypeScript for type safety.
- Tailwind CSS for styling.
- Lucide React for interface icons.
- Server Components for secure data fetching.
- Client Components for shopping cart interactions.
Start the development server.
npm run dev
Open:
http://localhost:3000
You should see the default Next.js starter application.
Step 6: Configure Your Environment Variables
Create a file named .env.local in the root of your project.
SHOPRIVET_API_URL=https://api.shoprivet.io
SHOPRIVET_API_KEY=shoprivet_live_YOUR_KEY
SHOPRIVET_STORE_ID=YOUR_STORE_ID
NEXT_PUBLIC_SHOPRIVET_API_URL=https://api.shoprivet.io
NEXT_PUBLIC_SHOPRIVET_STORE_SLUG=atelier-noir
Replace the example API key, store ID, and store slug with your actual credentials.
Restart the development server after changing environment variables.
Why Are Some Variables Public?
Next.js treats variables prefixed with NEXT_PUBLIC_ as values that can be included in the browser bundle.
Our storefront API URL and store slug aren't merchant secrets, so they can be public.
The merchant API key is different.
Never do this:
NEXT_PUBLIC_SHOPRIVET_API_KEY=your-secret-key
That would expose the merchant credential to users of your website.
Anyone who obtains a sufficiently privileged merchant API key could potentially perform unauthorized store operations.
Our private API key will remain on the Next.js server.
Make sure .env.local is excluded from Git.
You can read more about this in the Next.js environment variables documentation.
Step 7: Organize the Project Structure
We're going to use the following structure:
atelier-noir/
├── .env.local
├── public/
│ └── images/
│ └── hero.jpg
└── src/
├── app/
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├── components/
│ ├── storefront.tsx
│ ├── product-card.tsx
│ └── cart-panel.tsx
├── lib/
│ ├── shoprivet-server.ts
│ ├── shoprivet-public.ts
│ └── currency.ts
└── types/
└── commerce.ts
This separates our server-side API integration, browser-facing commerce requests, reusable UI components, and TypeScript definitions.
We don't need a Prisma schema, database migration, or separate REST API application.
Step 8: Define Our Commerce Types
Create src/types/commerce.ts.
These types represent the subset of Shoprivet's documented API responses that our storefront needs.
export interface Product {
id: string;
name: string;
slug: string;
description: string | null;
price: number;
comparePrice: number | null;
currency: string;
images: string[];
stock: number | null;
trackStock: boolean;
hasVariants: boolean;
}
export interface CartItem {
id: string;
productId?: string;
name?: string;
quantity: number;
unitPrice: number;
lineTotal: number;
}
export interface Cart {
id: string;
currency: string;
items: CartItem[];
subtotal: number;
total: number;
canCheckout: boolean;
}
export interface PaymentMethod {
provider: string;
label: string;
withoutOnlinePayment?: boolean;
}
export interface CheckoutResult {
success: boolean;
orderNumber: string;
authorizationUrl?: string;
orderAccessToken?: string;
paymentMethod: string;
payOnDelivery?: boolean;
order?: {
orderNumber: string;
status: string;
paymentStatus: string;
total: number;
currency: string;
};
}
These are application-specific types rather than an exhaustive SDK.
Check the current response examples in your Developers dashboard when extending the application.
Step 9: Create a Secure Shoprivet API Client
Create src/lib/shoprivet-server.ts.
This module will handle authenticated server-side requests.
import "server-only";
import type { Product } from "@/types/commerce";
const API_URL = process.env.SHOPRIVET_API_URL;
interface ManagementProduct
extends Omit<Product, "hasVariants"> {
status: string;
variants?: unknown[];
options?: unknown[];
}
interface ProductsResponse {
products: ManagementProduct[];
total: number;
page: number;
totalPages: number;
}
export async function getProducts(): Promise<Product[]> {
const apiKey = process.env.SHOPRIVET_API_KEY;
const storeId = process.env.SHOPRIVET_STORE_ID;
if (!API_URL || !apiKey || !storeId) {
throw new Error("Shoprivet credentials are missing.");
}
const response = await fetch(
`${API_URL}/v1/stores/${encodeURIComponent(storeId)}/products?page=1&limit=24`,
{
headers: {
Authorization: `Bearer ${apiKey}`,
Accept: "application/json",
},
next: {
revalidate: 60,
},
}
);
if (!response.ok) {
throw new Error(
`Unable to retrieve products (${response.status}).`
);
}
const data: ProductsResponse = await response.json();
return data.products
.filter((product) => product.status === "active")
.map((product) => ({
id: product.id,
name: product.name,
slug: product.slug,
description: product.description,
price: product.price,
comparePrice: product.comparePrice,
currency: product.currency,
images: product.images ?? [],
stock: product.stock,
trackStock: product.trackStock,
hasVariants: Boolean(
product.variants?.length || product.options?.length
),
}));
}
Let's understand what this code is doing.
First, the request sends our private API key through the Bearer authentication header.
Second, we retrieve products from the documented endpoint:
GET /v1/stores/STORE_ID/products
Third, we filter the results to published products and explicitly select the fields that can be passed to our customer-facing application.
Management API responses may contain fields that aren't intended for public use.
Avoid sending entire authenticated API responses to Client Components.
Finally, we enable a 60-second revalidation period to reduce unnecessary calls to the API.
The management API supports pagination using page and limit, with a documented maximum limit of 100.
This example displays the first 24 products. Larger catalogs should implement pagination and account for drafts or inactive products when constructing the visible catalog.
An alternative is to use the public product listing endpoint for the customer-facing catalog, which is preferable when you don't need authenticated access.
We're demonstrating the management API here so you can understand how to make secure authenticated requests from Next.js.
Step 10: Create Our Public Storefront API Client
Now we need a separate module for customer interactions.
Create src/lib/shoprivet-public.ts.
Unlike our previous module, this one does not use the merchant API key.
import type {
Cart,
CheckoutResult,
PaymentMethod,
} from "@/types/commerce";
const API_URL = process.env.NEXT_PUBLIC_SHOPRIVET_API_URL;
const STORE_SLUG =
process.env.NEXT_PUBLIC_SHOPRIVET_STORE_SLUG;
const BASE_URL =
`${API_URL}/public/stores/${encodeURIComponent(STORE_SLUG ?? "")}`;
export const CART_STORAGE_KEY =
`shoprivet:${STORE_SLUG}:cart`;
export const CHECKOUT_STORAGE_KEY =
`shoprivet:${STORE_SLUG}:checkout`;
export class CommerceError extends Error {
constructor(
message: string,
public status: number
) {
super(message);
this.name = "CommerceError";
}
}
async function request<T>(
path: string,
options: RequestInit = {},
credential?: string
): Promise<T> {
const headers = new Headers(options.headers);
headers.set("Accept", "application/json");
if (options.body) {
headers.set("Content-Type", "application/json");
}
if (credential) {
headers.set("Authorization", `Bearer ${credential}`);
}
const response = await fetch(`${BASE_URL}${path}`, {
...options,
headers,
credentials: "omit",
cache: "no-store",
});
const data =
response.status === 204
? null
: await response.json().catch(() => null);
if (!response.ok) {
throw new CommerceError(
typeof data?.message === "string"
? data.message
: `Commerce request failed (${response.status}).`,
response.status
);
}
return data as T;
}
export async function createCart() {
return request<{ credential: string }>("/carts", {
method: "POST",
});
}
export async function getCart(credential: string) {
return request<Cart>(
"/carts/current",
{},
credential
);
}
export async function addCartItem(
credential: string,
productId: string,
quantity = 1
) {
await request<unknown>(
"/carts/current/items",
{
method: "POST",
body: JSON.stringify({ productId, quantity }),
},
credential
);
return getCart(credential);
}
export async function updateCartItem(
credential: string,
itemId: string,
quantity: number
) {
await request<unknown>(
`/carts/current/items/${encodeURIComponent(itemId)}`,
{
method: "PATCH",
body: JSON.stringify({ quantity }),
},
credential
);
return getCart(credential);
}
export async function removeCartItem(
credential: string,
itemId: string
) {
await request<unknown>(
`/carts/current/items/${encodeURIComponent(itemId)}`,
{
method: "DELETE",
},
credential
);
return getCart(credential);
}
export async function getPaymentMethods() {
return request<{
currency: string;
methods: PaymentMethod[];
}>("/payment-methods");
}
export interface CheckoutInput {
name: string;
email: string;
provider: string;
idempotencyKey: string;
}
export async function checkout(
credential: string,
input: CheckoutInput
) {
return request<CheckoutResult>(
"/carts/current/checkout",
{
method: "POST",
body: JSON.stringify(input),
},
credential
);
}
This module gives our React components reusable functions for interacting with Shoprivet.
Notice that the Authorization header used here contains a guest cart credential, not the merchant API key.
That distinction is essential.
Understanding Server-Managed Guest Carts
A common approach when building a React ecommerce website is to store the entire shopping cart in localStorage.
That works for displaying items, but it introduces an important problem.
The browser is not a trusted environment.
A customer could modify local data, including prices, quantities, or product information.
Shoprivet provides a server-managed guest cart API instead.
When we create a cart:
POST /public/stores/STORE_SLUG/carts
The API returns a guest cart credential.
We then send that credential when retrieving or modifying the cart.
Authorization: Bearer GUEST_CART_CREDENTIAL
The server is responsible for validating products, checking stock, calculating prices, and determining whether the cart can proceed to checkout.
Our application only stores the credential needed to retrieve the customer's cart.
We don't treat browser-calculated prices as authoritative.
Guest credentials are scoped to their store and expire.
If an existing credential returns 401 or 410, the customer can start a new cart.
Because browser storage is accessible to JavaScript, protecting your application against cross-site scripting is still important.
Never store merchant API keys alongside guest cart credentials.
Step 11: Create a Currency Formatting Utility
Create src/lib/currency.ts.
export function formatMoney(
amount: number,
currency = "usd"
) {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: currency.toUpperCase(),
}).format(amount);
}
Using Intl.NumberFormat is preferable to manually adding a dollar sign to every product price.
Our API returns currency information, which allows the storefront to format prices appropriately for different stores.
Step 12: Design the Product Card
Now let's start building our storefront interface.
Create src/components/product-card.tsx.
import { Plus } from "lucide-react";
import type { Product } from "@/types/commerce";
import { formatMoney } from "@/lib/currency";
interface ProductCardProps {
product: Product;
onAdd: (productId: string) => void;
disabled?: boolean;
}
export default function ProductCard({
product,
onAdd,
disabled,
}: ProductCardProps) {
const soldOut =
product.trackStock &&
product.stock !== null &&
product.stock <= 0;
return (
<article className="group">
<div className="relative aspect-[3/4] overflow-hidden bg-stone-100">
{product.images[0] ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={product.images[0]}
alt={product.name}
loading="lazy"
className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
/>
) : (
<div className="flex h-full items-center justify-center text-sm text-stone-400">
Image unavailable
</div>
)}
{soldOut && (
<span className="absolute left-3 top-3 bg-white px-3 py-2 text-xs uppercase tracking-wide">
Sold out
</span>
)}
{!soldOut &&
product.comparePrice !== null &&
product.comparePrice > product.price && (
<span className="absolute left-3 top-3 bg-black px-3 py-2 text-xs uppercase text-white">
Sale
</span>
)}
</div>
<div className="flex items-start justify-between gap-3 py-4">
<div>
<h3 className="text-sm font-medium">
{product.name}
</h3>
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
<span>
{formatMoney(product.price, product.currency)}
</span>
{product.comparePrice !== null &&
product.comparePrice > product.price && (
<span className="text-stone-400 line-through">
{formatMoney(
product.comparePrice,
product.currency
)}
</span>
)}
</div>
</div>
<button
type="button"
aria-label={`Add ${product.name} to cart`}
disabled={
disabled || soldOut || product.hasVariants
}
onClick={() => onAdd(product.id)}
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-stone-300 transition hover:border-black hover:bg-black hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
>
<Plus size={18} />
</button>
</div>
{product.hasVariants && (
<p className="text-xs text-stone-500">
Product options required
</p>
)}
</article>
);
}
We've designed the product card to have:
- Large product photography.
- Minimal typography.
- A circular add-to-cart button.
- Discount pricing.
- Sold-out indicators.
- Responsive dimensions.
- Hover animations.
Products that require variant selection are intentionally disabled in this first implementation.
We'll need a variant selection component before allowing purchases of those products.
The browser's stock indicator is only a convenience. Shoprivet remains responsible for validating stock during cart operations and checkout.
For simplicity, we're using a standard HTML image element. In a production application, you could use Next.js Image after configuring the appropriate trusted remote image hosts.
Step 13: Build the Shopping Cart Interface
Create src/components/cart-panel.tsx.
Our shopping bag will display items, allow customers to update quantities, remove products, and proceed to checkout.
"use client";
import {
Minus,
Plus,
Trash2,
X,
ShoppingBag,
ArrowRight,
} from "lucide-react";
import type {
Cart,
Product,
} from "@/types/commerce";
import { formatMoney } from "@/lib/currency";
interface CartPanelProps {
cart: Cart | null;
products: Product[];
busy: boolean;
onClose: () => void;
onQuantityChange: (
itemId: string,
quantity: number
) => void;
onRemove: (itemId: string) => void;
onCheckout: () => void;
}
export default function CartPanel({
cart,
products,
busy,
onClose,
onQuantityChange,
onRemove,
onCheckout,
}: CartPanelProps) {
const items = cart?.items ?? [];
const currency = cart?.currency ?? "usd";
return (
<div className="fixed inset-0 z-50 flex justify-end">
<button
type="button"
aria-label="Close shopping bag"
onClick={onClose}
className="absolute inset-0 bg-black/40"
/>
<aside
role="dialog"
aria-label="Shopping bag"
className="relative flex h-full w-full max-w-md flex-col bg-white shadow-2xl"
>
<header className="flex items-center justify-between border-b border-stone-200 px-6 py-5">
<h2 className="font-serif text-2xl">
Shopping bag
</h2>
<button
type="button"
onClick={onClose}
aria-label="Close shopping bag"
>
<X size={22} />
</button>
</header>
<div className="flex-1 overflow-y-auto p-6">
{items.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-4 text-stone-500">
<ShoppingBag size={36} strokeWidth={1} />
<p>Your shopping bag is empty.</p>
<button
onClick={onClose}
className="border-b border-black text-sm text-black"
>
Continue shopping
</button>
</div>
) : (
items.map((item) => {
const product = products.find(
(p) => p.id === item.productId
);
return (
<div
key={item.id}
className="flex gap-4 border-b border-stone-200 py-5"
>
<div className="h-28 w-20 shrink-0 bg-stone-100">
{product?.images[0] && (
// eslint-disable-next-line @next/next/no-img-element
<img
src={product.images[0]}
alt={product.name}
className="h-full w-full object-cover"
/>
)}
</div>
<div className="flex flex-1 flex-col justify-between">
<div className="flex justify-between gap-3">
<h3 className="text-sm font-medium">
{item.name ??
product?.name ??
"Selected product"}
</h3>
<button
aria-label="Remove item"
disabled={busy}
onClick={() => onRemove(item.id)}
>
<Trash2 size={15} />
</button>
</div>
<p className="text-sm text-stone-500">
{formatMoney(
item.unitPrice,
currency
)}
</p>
<div className="flex items-center justify-between">
<div className="flex items-center border border-stone-300">
<button
aria-label="Decrease quantity"
disabled={
busy || item.quantity <= 1
}
onClick={() =>
onQuantityChange(
item.id,
item.quantity - 1
)
}
className="p-2 disabled:opacity-40"
>
<Minus size={14} />
</button>
<span className="px-3 text-sm">
{item.quantity}
</span>
<button
aria-label="Increase quantity"
disabled={
busy || item.quantity >= 99
}
onClick={() =>
onQuantityChange(
item.id,
item.quantity + 1
)
}
className="p-2 disabled:opacity-40"
>
<Plus size={14} />
</button>
</div>
<strong className="text-sm font-medium">
{formatMoney(
item.lineTotal,
currency
)}
</strong>
</div>
</div>
</div>
);
})
)}
</div>
{items.length > 0 && (
<footer className="border-t border-stone-200 p-6">
<div className="mb-2 flex justify-between">
<span>Subtotal</span>
<span>
{formatMoney(
cart?.subtotal ?? 0,
currency
)}
</span>
</div>
<div className="mb-6 flex justify-between text-lg font-medium">
<span>Cart total</span>
<span>
{formatMoney(
cart?.total ?? 0,
currency
)}
</span>
</div>
<button
disabled={busy || !cart?.canCheckout}
onClick={onCheckout}
className="flex w-full items-center justify-center gap-3 bg-black px-6 py-4 text-sm text-white disabled:opacity-40"
>
Proceed to checkout
<ArrowRight size={16} />
</button>
</footer>
)}
</aside>
</div>
);
}
The cart displays totals returned by Shoprivet rather than calculating authoritative totals from product prices stored in React.
The interface simply sends the customer's requested changes to the API.
For example, increasing an item quantity uses:
PATCH /public/stores/STORE_SLUG/carts/current/items/CART_ITEM_ID
Removing an item uses:
DELETE /public/stores/STORE_SLUG/carts/current/items/CART_ITEM_ID
This prevents us from having to implement the underlying cart management and validation logic ourselves.
Notice that cart item IDs are different from product IDs.
Use the cart item ID when updating or removing an existing line.
Step 14: Build the Main Next.js Storefront
Now we're ready to bring everything together.
First, add a fashion campaign photograph to:
public/images/hero.jpg
You can use an original photograph or an appropriately licensed image.
A wide editorial photograph featuring neutral clothing, minimal architecture, and natural lighting would work well with this design.
Create src/components/storefront.tsx.
"use client";
import {
useEffect,
useRef,
useState,
type FormEvent,
} from "react";
import {
ShoppingBag,
Search,
ArrowUpRight,
ArrowRight,
X,
CheckCircle2,
Package,
ShieldCheck,
} from "lucide-react";
import ProductCard from "./product-card";
import CartPanel from "./cart-panel";
import type {
Product,
Cart,
PaymentMethod,
CheckoutResult,
} from "@/types/commerce";
import {
CART_STORAGE_KEY,
CHECKOUT_STORAGE_KEY,
CommerceError,
createCart,
getCart,
addCartItem,
updateCartItem,
removeCartItem,
getPaymentMethods,
checkout,
type CheckoutInput,
} from "@/lib/shoprivet-public";
import { formatMoney } from "@/lib/currency";
export default function Storefront({
products,
}: {
products: Product[];
}) {
const [query, setQuery] = useState("");
const [cart, setCart] = useState<Cart | null>(null);
const [cartOpen, setCartOpen] = useState(false);
const [checkoutOpen, setCheckoutOpen] = useState(false);
const [ready, setReady] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [methods, setMethods] = useState<
PaymentMethod[]
>([]);
const [provider, setProvider] = useState("");
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [result, setResult] =
useState<CheckoutResult | null>(null);
const credential = useRef<string | null>(null);
const locked = useRef(false);
const pendingCheckout = useRef<CheckoutInput | null>(
null
);
useEffect(() => {
let mounted = true;
async function restoreCart() {
try {
const saved = localStorage.getItem(
CART_STORAGE_KEY
);
if (!saved) return;
credential.current = saved;
const existingCart = await getCart(saved);
if (mounted) {
setCart(existingCart);
}
} catch (err) {
if (!mounted) return;
if (
err instanceof CommerceError &&
[401, 410].includes(err.status)
) {
localStorage.removeItem(CART_STORAGE_KEY);
credential.current = null;
} else {
setError("Unable to restore your shopping bag.");
}
} finally {
if (mounted) setReady(true);
}
}
void restoreCart();
return () => {
mounted = false;
};
}, []);
async function run(
action: () => Promise<void>
) {
if (locked.current) return;
locked.current = true;
setBusy(true);
setError("");
try {
await action();
} catch (err) {
if (
err instanceof CommerceError &&
[401, 410].includes(err.status)
) {
localStorage.removeItem(CART_STORAGE_KEY);
credential.current = null;
setCart(null);
setError(
"Your shopping bag has expired. Please add your products again."
);
} else {
setError(
err instanceof Error
? err.message
: "Something went wrong. Please try again."
);
}
} finally {
locked.current = false;
setBusy(false);
}
}
async function ensureCart() {
if (credential.current) {
return credential.current;
}
const created = await createCart();
credential.current = created.credential;
localStorage.setItem(
CART_STORAGE_KEY,
created.credential
);
return created.credential;
}
function addProduct(productId: string) {
void run(async () => {
const token = await ensureCart();
const updated = await addCartItem(
token,
productId,
1
);
setCart(updated);
setCartOpen(true);
setResult(null);
});
}
function changeQuantity(
itemId: string,
quantity: number
) {
void run(async () => {
if (!credential.current) return;
const updated = await updateCartItem(
credential.current,
itemId,
quantity
);
setCart(updated);
});
}
function removeProduct(itemId: string) {
void run(async () => {
if (!credential.current) return;
const updated = await removeCartItem(
credential.current,
itemId
);
setCart(updated);
});
}
function openCheckout() {
void run(async () => {
if (!cart?.canCheckout) return;
const data = await getPaymentMethods();
if (!data.methods.length) {
throw new Error(
"No payment methods are available."
);
}
setMethods(data.methods);
setProvider(data.methods[0].provider);
setCartOpen(false);
setCheckoutOpen(true);
});
}
function placeOrder(
event: FormEvent<HTMLFormElement>
) {
event.preventDefault();
void run(async () => {
if (!credential.current || !cart?.canCheckout) {
throw new Error(
"Your shopping bag is not ready for checkout."
);
}
if (!provider) {
throw new Error("Select a payment method.");
}
// Keep the same payload and idempotency key
// when retrying an unresolved checkout.
if (!pendingCheckout.current) {
pendingCheckout.current = {
name: name.trim(),
email: email.trim(),
provider,
idempotencyKey: crypto.randomUUID(),
};
}
const response = await checkout(
credential.current,
pendingCheckout.current
);
if (!response.success) {
throw new Error(
"Checkout was not completed."
);
}
// Retain the limited order credential for
// authorized order lookup after payment.
if (response.orderAccessToken) {
sessionStorage.setItem(
CHECKOUT_STORAGE_KEY,
JSON.stringify({
orderNumber: response.orderNumber,
orderAccessToken:
response.orderAccessToken,
})
);
}
if (response.authorizationUrl) {
window.location.assign(
response.authorizationUrl
);
return;
}
setResult(response);
setCheckoutOpen(false);
setCartOpen(false);
pendingCheckout.current = null;
credential.current = null;
localStorage.removeItem(CART_STORAGE_KEY);
setCart(null);
});
}
const filteredProducts = products.filter((product) =>
product.name
.toLowerCase()
.includes(query.toLowerCase())
);
const itemCount =
cart?.items.reduce(
(total, item) => total + item.quantity,
0
) ?? 0;
return (
<div className="min-h-screen bg-white text-stone-900">
<div className="bg-stone-900 px-4 py-3 text-center text-[10px] uppercase tracking-[0.25em] text-white">
Thoughtfully selected. Timeless by design.
</div>
<header className="sticky top-0 z-30 border-b border-stone-200 bg-white">
<nav className="mx-auto flex h-20 max-w-[1440px] items-center justify-between px-5 md:px-12">
<a
href="#"
className="font-serif text-xl tracking-[0.2em] md:text-2xl"
>
ATELIER NOIR
</a>
<div className="hidden items-center gap-9 text-xs uppercase tracking-widest md:flex">
<a href="#collection">Collection</a>
<a href="#about">Our philosophy</a>
</div>
<button
type="button"
disabled={!ready}
onClick={() => setCartOpen(true)}
className="flex items-center gap-3"
aria-label={`Shopping bag, ${itemCount} items`}
>
<ShoppingBag
size={21}
strokeWidth={1.5}
/>
<span className="text-xs">
({itemCount})
</span>
</button>
</nav>
</header>
<main>
<section className="grid min-h-[540px] bg-[#f3f1ed] md:grid-cols-2">
<div className="flex flex-col justify-center px-8 py-16 md:px-16 lg:px-24">
<p className="mb-6 text-[10px] uppercase tracking-[0.3em] text-stone-600">
The everyday collection
</p>
<h1 className="max-w-xl font-serif text-5xl leading-[1.05] md:text-6xl lg:text-7xl">
Less, but
<br />
considered.
</h1>
<p className="mt-7 max-w-sm text-sm leading-7 text-stone-600">
A collection of contemporary essentials
designed to fit effortlessly into your
everyday life.
</p>
<a
href="#collection"
className="mt-9 inline-flex w-fit items-center gap-8 bg-black px-7 py-4 text-xs uppercase tracking-widest text-white transition hover:bg-stone-700"
>
Explore collection
<ArrowUpRight size={16} />
</a>
</div>
<div className="relative min-h-[400px] overflow-hidden">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/images/hero.jpg"
alt="Atelier Noir fashion collection"
className="absolute inset-0 h-full w-full object-cover"
/>
</div>
</section>
<section
id="collection"
className="mx-auto max-w-[1440px] scroll-mt-24 px-5 py-20 md:px-12"
>
<div className="mb-10 flex flex-col justify-between gap-6 md:flex-row md:items-end">
<div>
<p className="mb-3 text-[10px] uppercase tracking-[0.25em] text-stone-500">
Curated essentials
</p>
<h2 className="font-serif text-4xl md:text-5xl">
Discover the collection
</h2>
<p className="mt-4 text-sm text-stone-500">
Explore pieces made for your everyday wardrobe.
</p>
</div>
<div className="relative w-full md:w-64">
<Search
size={17}
className="absolute left-3 top-3 text-stone-400"
/>
<input
type="search"
aria-label="Search products"
placeholder="Search products"
value={query}
onChange={(event) =>
setQuery(event.target.value)
}
className="w-full border border-stone-300 py-3 pl-10 pr-4 text-sm outline-none focus:border-black"
/>
</div>
</div>
<div className="mb-6 text-xs uppercase tracking-widest text-stone-500">
{filteredProducts.length} products
</div>
<div className="grid grid-cols-2 gap-x-5 gap-y-10 md:grid-cols-3 lg:grid-cols-4">
{filteredProducts.map((product) => (
<ProductCard
key={product.id}
product={product}
onAdd={addProduct}
disabled={!ready || busy || Boolean(checkoutOpen)}
/>
))}
</div>
{!filteredProducts.length && (
<div className="py-20 text-center text-stone-500">
No matching products found.
</div>
)}
</section>
<section
id="about"
className="bg-[#f3f1ed] px-6 py-24 text-center"
>
<p className="mb-5 text-[10px] uppercase tracking-[0.3em] text-stone-500">
Our philosophy
</p>
<h2 className="mx-auto max-w-3xl font-serif text-4xl leading-tight md:text-5xl">
Good design begins with the things we choose to keep.
</h2>
<p className="mx-auto mt-6 max-w-xl text-sm leading-7 text-stone-600">
Atelier Noir is an exploration of simplicity,
individuality, and the beauty of everyday essentials.
</p>
</section>
<section className="mx-auto grid max-w-6xl gap-8 px-6 py-12 text-center sm:grid-cols-2">
<div className="flex flex-col items-center gap-3">
<Package
size={23}
strokeWidth={1.3}
/>
<h3 className="text-sm font-medium">
Order management
</h3>
<p className="text-xs text-stone-500">
Orders processed through our commerce platform.
</p>
</div>
<div className="flex flex-col items-center gap-3">
<ShieldCheck
size={23}
strokeWidth={1.3}
/>
<h3 className="text-sm font-medium">
Secure checkout
</h3>
<p className="text-xs text-stone-500">
Payments through supported payment providers.
</p>
</div>
</section>
</main>
<footer className="bg-stone-900 px-6 py-16 text-white md:px-12">
<div className="mx-auto flex max-w-[1440px] flex-col justify-between gap-8 md:flex-row">
<div>
<h2 className="font-serif text-2xl tracking-widest">
ATELIER NOIR
</h2>
<p className="mt-4 max-w-xs text-sm leading-6 text-stone-400">
Contemporary essentials for everyday living.
</p>
</div>
<div className="flex flex-col gap-4 text-sm text-stone-300">
<a href="#collection">Shop the collection</a>
<a href="#about">About Atelier Noir</a>
<a
href="https://shoprivet.io"
className="text-stone-400"
>
Commerce powered by Shoprivet
</a>
</div>
</div>
</footer>
{cartOpen && (
<CartPanel
cart={cart}
products={products}
busy={busy}
onClose={() => setCartOpen(false)}
onQuantityChange={changeQuantity}
onRemove={removeProduct}
onCheckout={openCheckout}
/>
)}
{checkoutOpen && (
<div className="fixed inset-0 z-[60] flex items-center justify-center overflow-y-auto bg-black/50 p-4">
<section
role="dialog"
aria-label="Checkout"
className="max-h-[90vh] w-full max-w-lg overflow-y-auto bg-white p-7 md:p-10"
>
<div className="mb-7 flex items-center justify-between">
<h2 className="font-serif text-3xl">
Checkout
</h2>
<button
disabled={busy}
aria-label="Close checkout"
onClick={() => {
if (pendingCheckout.current) {
setError(
"Resolve the pending checkout before changing your order."
);
return;
}
setCheckoutOpen(false);
}}
>
<X size={22} />
</button>
</div>
<form
onSubmit={placeOrder}
className="space-y-5"
>
<div>
<label
htmlFor="customer-name"
className="mb-2 block text-sm"
>
Full name
</label>
<input
id="customer-name"
required
autoComplete="name"
disabled={
busy || Boolean(pendingCheckout.current)
}
value={name}
onChange={(event) =>
setName(event.target.value)
}
className="w-full border border-stone-300 p-3 outline-none focus:border-black"
/>
</div>
<div>
<label
htmlFor="customer-email"
className="mb-2 block text-sm"
>
Email address
</label>
<input
id="customer-email"
required
type="email"
autoComplete="email"
disabled={
busy || Boolean(pendingCheckout.current)
}
value={email}
onChange={(event) =>
setEmail(event.target.value)
}
className="w-full border border-stone-300 p-3 outline-none focus:border-black"
/>
</div>
<fieldset>
<legend className="mb-3 text-sm">
Payment method
</legend>
<div className="space-y-3">
{methods.map((method) => (
<label
key={method.provider}
className="flex cursor-pointer items-center gap-3 border border-stone-300 p-4 text-sm"
>
<input
type="radio"
name="payment-method"
value={method.provider}
checked={
provider === method.provider
}
disabled={
busy ||
Boolean(pendingCheckout.current)
}
onChange={() =>
setProvider(method.provider)
}
/>
{method.label}
</label>
))}
</div>
</fieldset>
<div className="flex justify-between border-t border-stone-200 pt-5 text-sm">
<span>Cart total</span>
<strong>
{formatMoney(
cart?.total ?? 0,
cart?.currency ?? "usd"
)}
</strong>
</div>
<button
disabled={busy}
type="submit"
className="flex w-full items-center justify-center gap-3 bg-black py-4 text-sm text-white disabled:opacity-50"
>
{busy
? "Processing..."
: pendingCheckout.current
? "Retry checkout"
: "Place order"}
{!busy && <ArrowRight size={17} />}
</button>
</form>
</section>
</div>
)}
{result && (
<div
role="status"
className="fixed bottom-5 right-5 z-[70] max-w-sm border border-stone-200 bg-white p-6 shadow-xl"
>
<CheckCircle2
size={28}
className="mb-3 text-green-700"
/>
<h3 className="font-serif text-2xl">
Order received
</h3>
<p className="mt-3 text-sm text-stone-600">
Order number: {result.orderNumber}
</p>
<p className="mt-2 text-sm">
Payment status:{" "}
{result.order?.paymentStatus ?? "Not confirmed"}
</p>
{result.payOnDelivery && (
<p className="mt-2 text-sm text-stone-600">
Payment is due on delivery.
</p>
)}
<button
onClick={() => setResult(null)}
className="mt-5 border-b border-black text-sm"
>
Continue shopping
</button>
</div>
)}
{error && (
<div
role="alert"
className="fixed bottom-5 left-5 right-5 z-[80] flex max-w-md items-start justify-between gap-4 border border-red-200 bg-white p-4 text-sm text-red-700 shadow-xl"
>
<span>{error}</span>
<button
aria-label="Dismiss error"
onClick={() => setError("")}
>
<X size={18} />
</button>
</div>
)}
</div>
);
}
This is the main interactive component of our ecommerce website.
It handles:
- Searching products.
- Creating a guest cart when needed.
- Restoring an existing cart after refreshing the page.
- Adding products.
- Updating quantities.
- Removing products.
- Loading available payment methods.
- Customer checkout.
- Redirecting customers to payment providers.
- Displaying order confirmation.
- Handling errors and preventing overlapping operations.
The important thing is that we're only implementing the shopping experience.
Shoprivet is responsible for the underlying commerce operations.
A Note About This Checkout Example
We've kept the initial checkout form close to the documented basic API example, which uses the customer's name, email, selected provider, and idempotency key.
For a production physical-product store, you should also implement any required shipping address fields, phone number, delivery options, taxes, and applicable disclosures using the current checkout API schema.
Our minimal example should not be treated as a complete shipping and tax implementation.
Why Do We Use an Idempotency Key?
Imagine a customer clicks Place order, but their internet connection temporarily fails.
The server may have received the request even though the browser didn't receive a successful response.
Immediately sending a completely new checkout request could create unintended duplicate orders.
Shoprivet's checkout documentation supports an idempotency key.
crypto.randomUUID()
We generate this key once for a particular checkout attempt and reuse it when retrying the same request.
Our example preserves the pending checkout in memory while the page remains open.
A production implementation should persist unresolved checkout attempts securely across page reloads and provide an explicit recovery flow before allowing a new checkout attempt.
Do not automatically generate a new idempotency key when the outcome of the previous request is uncertain.
Step 15: Connect the Server Component to Our Storefront
Open src/app/page.tsx.
Replace its contents with:
import Storefront from "@/components/storefront";
import { getProducts } from "@/lib/shoprivet-server";
export default async function Home() {
const products = await getProducts();
return <Storefront products={products} />;
}
This page is a Next.js Server Component.
It retrieves our product catalog from Shoprivet using the merchant API key.
Only the selected product fields are passed to the interactive Storefront component.
The private API key never becomes part of the browser bundle.
This is one of the advantages of using Next.js for headless ecommerce.
You can combine secure server-side requests with interactive client-side components within the same application.
You don't need to deploy a separate service simply to retrieve product information.
For more information, see the official Next.js Server and Client Components documentation.
Step 16: Configure the Global Layout and Typography
Open src/app/layout.tsx.
import type { Metadata } from "next";
import { DM_Sans, Cormorant_Garamond } from "next/font/google";
import "./globals.css";
const sans = DM_Sans({
subsets: ["latin"],
variable: "--font-store-sans",
});
const serif = Cormorant_Garamond({
subsets: ["latin"],
weight: ["400", "500", "600"],
variable: "--font-store-serif",
});
export const metadata: Metadata = {
title: "Atelier Noir | Contemporary Essentials",
description:
"Discover contemporary clothing and everyday essentials at Atelier Noir.",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${sans.variable} ${serif.variable} antialiased`}
>
{children}
</body>
</html>
);
}
We're using two complementary typefaces:
- DM Sans for navigation, buttons, and body text.
- Cormorant Garamond for large editorial headings.
Now update src/app/globals.css.
This example uses Tailwind CSS 4 syntax.
@import "tailwindcss";
@theme inline {
--font-sans: var(--font-store-sans);
--font-serif: var(--font-store-serif);
}
html {
scroll-behavior: smooth;
}
body {
background: #ffffff;
color: #1c1917;
font-family: var(--font-store-sans), sans-serif;
}
button:not(:disabled) {
cursor: pointer;
}
button,
a,
input {
-webkit-tap-highlight-color: transparent;
}
button:focus-visible,
a:focus-visible,
input:focus-visible {
outline: 2px solid #78716c;
outline-offset: 4px;
}
::selection {
background: #1c1917;
color: #ffffff;
}
Our visual direction intentionally avoids unnecessary gradients, excessive rounded cards, and complicated animations.
The typography, whitespace, and product photography create the character of the storefront.
Because we're building our own interface, we have complete control over these design decisions.
Step 17: Configure Payment Methods in Shoprivet
We've implemented the frontend checkout experience, but we still need to configure how the merchant receives payments.
Return to your Shoprivet dashboard.
Navigate to Store settings and locate the payment configuration section.

Depending on your store configuration and merchant eligibility, available options can include:
- Stripe.
- Paystack.
- Flutterwave.
- Razorpay.
- PayPal.
- Cash on delivery.
Select the payment provider appropriate for your business.
For example, if you're using Stripe, configure your Stripe merchant account through the dashboard.

Follow the provided configuration instructions, including any required webhook setup.
For supported payment gateways, the public API documentation describes the webhook route using this structure:
https://api.shoprivet.io/public/stores/STORE_SLUG/payments/PROVIDER/webhook
Use the exact provider-specific configuration displayed in your dashboard.
Never place payment provider secret keys in customer-facing Next.js components.
How Are Payment Methods Loaded?
You may have noticed that we didn't hardcode Stripe or Paystack into the checkout form.
Instead, we retrieve the available methods from:
GET /public/stores/STORE_SLUG/payment-methods
An example response from the documentation looks like this:
{
"currency": "usd",
"methods": [
{
"provider": "cash_on_delivery",
"label": "Cash on delivery",
"withoutOnlinePayment": true
}
]
}
Our React component renders these available methods dynamically.
This allows the merchant to manage payment configurations independently of the frontend code.
Step 18: Test the Custom Storefront
Start your Next.js application.
npm run dev
Open http://localhost:3000 in your browser.
If your environment variables are correct and the store has published products, the storefront should retrieve and display your catalog.
<!-- Add an actual screenshot of the completed Atelier Noir Next.js homepage here. -->
You should now have a custom online store featuring your own:
- Navigation.
- Hero section.
- Typography.
- Product grid.
- Product photography.
- Search functionality.
- Shopping cart.
- Checkout interface.
None of these components were generated using Shoprivet's storefront builder.
They're all part of our custom Next.js application.
Test Adding Products to the Cart
Click the plus icon on any available product.
The first time a customer adds a product, the application creates a guest cart through Shoprivet.
It then adds the selected product to that cart using:
POST /public/stores/STORE_SLUG/carts/current/items
The cart response is retrieved and displayed in our shopping bag.
<!-- Add a screenshot of the custom Next.js shopping cart drawer here. -->
Try the following:
- Add a product.
- Add another product.
- Increase a product quantity.
- Decrease the quantity.
- Remove an item.
- Refresh the browser.
The shopping cart should be restored using the saved guest credential, provided the cart is still valid.
You should also test what happens when stock becomes unavailable.
Step 19: Place Your First Test Order
For the simplest initial test, enable cash on delivery in your store if it is available.
This allows you to test order creation without immediately configuring a card payment workflow.
Open your shopping bag and click Proceed to checkout.
Enter your customer details and select an available payment method.
<!-- Add a screenshot of the custom Next.js checkout interface here. -->
When you submit the form, our application calls:
POST /public/stores/STORE_SLUG/carts/current/checkout
The basic request follows this structure:
{
"name": "Demo Customer",
"email": "[email protected]",
"provider": "cash_on_delivery",
"idempotencyKey": "YOUR_UNIQUE_CHECKOUT_KEY"
}
Shoprivet already has access to the products in the server-managed cart.
The application doesn't need to send browser-calculated prices or an authoritative order total.
An example response for a cash-on-delivery order looks like this:
{
"success": true,
"orderNumber": "SRV-20260919-0001",
"paymentMethod": "cash_on_delivery",
"payOnDelivery": true,
"order": {
"orderNumber": "SRV-20260919-0001",
"status": "pending",
"paymentStatus": "unpaid",
"total": 35,
"currency": "usd"
}
}
This is a shortened illustrative response based on the API documentation.
Notice that a successful order creation does not necessarily mean that payment has been received.
A cash-on-delivery order can be successfully created while its payment status remains unpaid.
Our storefront displays an order-received message rather than incorrectly telling the customer that payment has been completed.
Step 20: Handle Online Payment Confirmation
When using an online payment provider, the checkout API may return an authorization URL.
Our frontend redirects the customer using:
window.location.assign(response.authorizationUrl);
The customer completes the payment through the provider's supported payment interface.
After payment, the customer returns to the appropriate store or configured payment return flow.
However, returning from a payment provider does not automatically prove that the payment was successful.
The payment must be verified.
Shoprivet provides a payment confirmation endpoint:
POST /public/stores/STORE_SLUG/orders/ORDER_NUMBER/confirm
The request uses the limited order access token returned by the checkout flow.
For example:
interface ConfirmPaymentInput {
storeSlug: string;
orderNumber: string;
orderAccessToken: string;
reference: string;
}
async function confirmPayment({
storeSlug,
orderNumber,
orderAccessToken,
reference,
}: ConfirmPaymentInput) {
const response = await fetch(
`https://api.shoprivet.io/public/stores/${encodeURIComponent(storeSlug)}/orders/${encodeURIComponent(orderNumber)}/confirm`,
{
method: "POST",
credentials: "omit",
headers: {
Authorization: `Bearer ${orderAccessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ reference }),
}
);
if (!response.ok) {
throw new Error("Payment could not be confirmed.");
}
return response.json();
}
The reference must come from the appropriate payment provider's real return flow.
Do not invent payment references or treat a query parameter such as success=true as proof of payment.
Retrieving an Existing Order
Shoprivet also provides a protected order lookup endpoint.
async function getOrder(
storeSlug: string,
orderNumber: string,
orderAccessToken: string
) {
const response = await fetch(
`https://api.shoprivet.io/public/stores/${encodeURIComponent(storeSlug)}/orders/${encodeURIComponent(orderNumber)}`,
{
credentials: "omit",
headers: {
Authorization: `Bearer ${orderAccessToken}`,
},
cache: "no-store",
}
);
if (!response.ok) {
throw new Error("Unable to retrieve order.");
}
return response.json();
}
An order confirmation page can use this function to retrieve the latest order information.
Only show a payment-completed message when the verified response indicates:
order.paymentStatus === "paid"
Your payment integration should also configure provider webhooks as documented.
Webhooks allow payment information to be processed independently of whether the customer successfully returns to the website.
Custom Payment Return Pages
To support online payments entirely within your own custom Next.js storefront, configure the return flow according to the payment provider and Shoprivet's supported callback configuration.
For example, your application could have a route such as:
/checkout/return
That route would:
- Retrieve the relevant order access credential.
- Read the provider-specific payment reference.
- Call the payment confirmation endpoint.
- Retrieve the verified order information.
- Display the actual payment status.
- Clear the completed cart when appropriate.
The exact callback configuration and return query parameters can differ across providers.
Confirm these details before implementing your custom return page.
The checkout example in this article demonstrates payment initiation. It does not assume an undocumented callback URL parameter or provide a universal callback implementation for every payment gateway.
Step 21: Manage Your Orders From the Shoprivet Dashboard
Return to your Shoprivet dashboard after placing a test order.
Navigate to Orders.

Your merchant can review purchases without accessing the Next.js source code.
Open an individual order to view the customer and purchase information.

Depending on the order, the merchant can manage its fulfillment progress through the available status controls.
The dashboard also provides a centralized interface for ongoing ecommerce operations.
Shoprivet supports order notifications, allowing merchants to receive notifications about new purchases.

This is particularly useful when you're building a custom website for a client.
You don't have to develop an entire administrative dashboard before handing over the website.
Your client can manage their products, inventory, and orders through Shoprivet.
You can concentrate on maintaining the customer-facing Next.js application.
How to Create Products Programmatically
So far, we've created products through the dashboard.
However, the Developers documentation also allows you to create and manage products programmatically.
This can be useful if you're migrating products from another system or building an internal merchant application.
For example, create a server-side script called scripts/create-product.mjs.
const apiKey = process.env.SHOPRIVET_API_KEY;
const storeId = process.env.SHOPRIVET_STORE_ID;
if (!apiKey || !storeId) {
throw new Error("Missing Shoprivet credentials.");
}
const response = await fetch(
`https://api.shoprivet.io/v1/stores/${encodeURIComponent(storeId)}/products`,
{
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Essential Cotton Tee",
price: 35,
type: "physical",
status: "active",
}),
}
);
if (!response.ok) {
throw new Error(
`Product creation failed (${response.status}).`
);
}
const product = await response.json();
console.log("Product created:", product.id);
Run the script using a Node.js version that supports --env-file.
node --env-file=.env.local scripts/create-product.mjs
This request creates a new product in your actual store.
Only run it when you intend to create the product, preferably while working with a dedicated test store.
You can then complete additional product information and photography through the dashboard.
The important point is that this operation happens in a private administrative script, not in a public React component.
What Else Can You Do With the Shoprivet Management API?
The documented versioned REST API provides several endpoints for administrative operations.
| Method | Endpoint | Purpose | |---|---|---| | GET | /v1/stores | List stores | | POST | /v1/stores | Create a store | | PATCH | /v1/stores/STORE_ID | Update a store | | GET | /v1/stores/STORE_ID/products | List products | | GET | /v1/stores/STORE_ID/products/PRODUCT_ID | Retrieve a product | | POST | /v1/stores/STORE_ID/products | Create a product | | PATCH | /v1/stores/STORE_ID/products/PRODUCT_ID | Update a product | | DELETE | /v1/stores/STORE_ID/products/PRODUCT_ID | Delete a product | | GET | /v1/stores/STORE_ID/categories | List categories | | POST | /v1/stores/STORE_ID/categories | Create a category | | DELETE | /v1/stores/STORE_ID/categories/CATEGORY_ID | Delete a category | | GET | /v1/stores/STORE_ID/orders | List orders | | POST | /v1/stores/STORE_ID/orders | Create an administrative order | | PATCH | /v1/stores/STORE_ID/orders/ORDER_ID/status | Update order status | | DELETE | /v1/stores/STORE_ID/orders/ORDER_ID | Delete an order |
Updates use the PATCH method rather than PUT.
The list endpoints support pagination.
These endpoints make it possible to build additional applications around your ecommerce infrastructure.
For example:
- An internal product management application.
- A product import utility.
- A custom fulfillment dashboard.
- An order reporting tool.
- A React Native shopping application.
- An inventory synchronization service.
- A multi-store management application.
The administrative order creation endpoint is different from customer checkout.
Creating an administrative order does not mean that a payment has been processed.
Always use the appropriate public checkout workflow for customer purchases.
Can You Add Product Variants to This Next.js Store?
Yes.
Shoprivet supports product options and variants on eligible Premium and Business plans.
For example, we could sell the Essential Cotton Tee in different sizes and colors.
Available Product Options
Size
├── Small
├── Medium
└── Large
Color
├── Black
├── White
└── Beige
Different variants can have their own:
- Price.
- Stock.
- SKU.
- Product images.
Shoprivet also documents different option display types:
- Text.
- Color.
- Image.
- Dropdown.
A custom React storefront can use these descriptions to determine how options should be rendered.
When the customer selects a particular variant, the add-to-cart request can include the selected variant ID and options.
const response = await fetch(
`https://api.shoprivet.io/public/stores/atelier-noir/carts/current/items`,
{
method: "POST",
credentials: "omit",
headers: {
Authorization: `Bearer ${cartCredential}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
productId: "PRODUCT_ID",
variantId: "VARIANT_ID",
options: {
Size: "M",
},
quantity: 1,
}),
}
);
if (!response.ok) {
throw new Error("Unable to add selected variant.");
}
Shoprivet validates the selected variant, options, pricing, and stock on the server.
Your application should present accurate available choices, but it should not attempt to override the backend's validation.
This is an example of how you can extend the starter storefront into a more advanced ecommerce application.
Can You Sell Digital Products Instead?
The same architecture can be used to sell digital products.
Instead of choosing a physical-product store, create an appropriate digital-product store.
Examples of digital products include:
- Website templates.
- Ebooks.
- Design assets.
- UI kits.
- Educational resources.
- Downloadable software resources.
Shoprivet's public storefront documentation describes unique download links for paid digital orders.
After a successful verified payment, the authorized order response can contain downloadable resources.
The documentation describes links that expire after 90 days and allow up to 20 downloads.
Don't expose paid download resources through public product URLs.
Use the protected download links issued through the verified order workflow.
Can You Build This With Only the Public API?
Yes.
If you only need customer-facing commerce functionality, you may not need a merchant API key in your storefront application at all.
For example, retrieving published products can use:
async function getPublicProducts(slug: string) {
const response = await fetch(
`https://api.shoprivet.io/public/stores/${encodeURIComponent(slug)}/products?page=1&limit=24`
);
if (!response.ok) {
throw new Error("Unable to load products.");
}
return response.json();
}
You can then use the public storefront API for guest carts, available payment methods, and checkout.
This is an important distinction for developers who want to build a frontend-only ecommerce application.
Our primary tutorial uses the management API to demonstrate secure API-key integration and server-rendered product data.
But applications that don't require authenticated merchant operations can use the public API instead.
You could apply that approach to:
- A React and Vite application.
- A static JavaScript website.
- An Astro website.
- A Vue application.
- A Next.js static export, with suitable client-side fetching.
The underlying commerce infrastructure remains the same.
Deploy Your Next.js Storefront
Once you're satisfied with your application, you can deploy it to a Next.js-compatible hosting platform such as Vercel.
Before deploying, run a production build.
npm run build
You can test the production server locally using:
npm run start
Push the application source code to your Git repository.
Do not commit your .env.local file.
Create a new project on Vercel and import your repository.
Add the following environment variables through the hosting platform's environment configuration.
SHOPRIVET_API_URL=https://api.shoprivet.io
SHOPRIVET_API_KEY=YOUR_PRIVATE_API_KEY
SHOPRIVET_STORE_ID=YOUR_STORE_ID
NEXT_PUBLIC_SHOPRIVET_API_URL=https://api.shoprivet.io
NEXT_PUBLIC_SHOPRIVET_STORE_SLUG=YOUR_STORE_SLUG
Deploy the application.
Since our main application uses authenticated server-side product fetching and revalidation, deploy it with Next.js server runtime support rather than assuming that a static export will work unchanged.
Once deployed, test the product catalog, shopping cart, checkout, and order management workflow again.
The production website may behave differently from localhost due to environment configuration, allowed origins, payment configuration, or callback requirements.
How to Improve Your Next.js Store's SEO
One advantage of building your own ecommerce storefront with Next.js is that you can control how your website's pages and content are rendered.
In this tutorial, we retrieve the initial product data on the server.
However, a complete ecommerce SEO strategy involves more than rendering a product grid.
A production storefront should consider:
Individual Product Pages
Create dedicated routes for each product.
For example:
/products/essential-cotton-tee
/products/relaxed-linen-shirt
/products/structured-blazer
Each page can have its own:
- Product title.
- Description.
- Product photographs.
- Metadata.
- Canonical URL.
- Product structured data.
Category Pages
You can also create pages targeting specific product categories.
/collections/essentials
/collections/outerwear
/collections/accessories
These pages could use the public product API's category filtering functionality.
Product Structured Data
Product structured data can help search engines understand information such as pricing, availability, product identifiers, and currency.
Make sure your structured data reflects the actual visible product information and current availability.
Do not add fake product ratings or reviews.
Product Updates
Because we retrieve products from Shoprivet, the frontend can pick up updated product information when its cached data revalidates.
The merchant doesn't need to manually change prices in the React source code.
You can adjust your revalidation strategy based on the freshness requirements and API usage of your store.
Why This Approach Is Useful for Developers and Agencies
Imagine you're a freelance developer who builds ecommerce websites for different clients.
One client sells fashion products.
Another sells furniture.
A third sells digital resources.
All three businesses need a unique storefront design, but their underlying commerce requirements are similar.
Instead of building and maintaining three different e-commerce backends, you could create a reusable Next.js integration around the Shoprivet API.
Each client could have:
- Their own store.
- Their own products.
- Their own payment configuration.
- Their own orders.
- A custom Next.js frontend.
- A merchant dashboard.
Shoprivet supports additional stores on eligible paid plans.
This creates a practical separation between the frontend development work and the merchant's ongoing ecommerce operations.
Each client's API credentials, store ownership, and payment provider accounts should be managed appropriately and kept separate.
Building Your Own Backend vs Using a Headless Commerce API
When deciding how to develop an ecommerce application, consider where most of the engineering effort will go.
| Requirement | Custom ecommerce backend | Shoprivet API | |---|---|---| | Product database | Design and maintain it | Managed through Shoprivet | | Inventory management | Implement business rules | Provided | | Product categories | Develop database and API | Provided | | Shopping carts | Implement and persist carts | Guest cart API | | Checkout | Develop checkout logic | Public checkout API | | Payment integrations | Individually implement providers | Configure supported integrations | | Order dashboard | Build an administrative application | Provided | | Product variants | Design and validate variant relationships | Available on eligible plans | | API security | Implement authentication and authorization | Managed API credentials | | Frontend design | Full control | Full control with custom API integration | | Backend hosting | Maintain separate infrastructure | Managed commerce infrastructure |
Building your own commerce backend may make sense if your application requires highly specialized transactional workflows.
However, if you're building a conventional online store, using established commerce functionality can reduce the amount of infrastructure you need to implement and maintain.
You should still evaluate the API's capabilities, pricing, availability, security requirements, and any business-specific limitations.
How Much Does It Cost?
Shoprivet offers free and paid plans.
| Feature | Free | Premium | Business | |---|---:|---:|---:| | Monthly subscription | $0 | $15 | $39 | | Stores | 1 | 3 | Unlimited | | Products | 25 | Unlimited | Unlimited | | Order allowance | 50 | 1,000 | 10,000 |
Product variants and other advanced features are available on eligible paid plans.
Review the current plan limits and API entitlements on the Shoprivet pricing page.
Shoprivet does not add its own percentage-based platform sales commission to purchases.
Your connected payment gateway may still charge processing fees.
You'll also need to account for your Next.js hosting expenses and other operational business costs.
For commercial projects, choose a hosting plan that permits your intended use.
Common Issues and How to Troubleshoot Them
The API Returns 401 Unauthorized
If you're making a management API request, verify that:
- Your API key is correct.
- The key has not been revoked.
- You're sending the Bearer authentication header.
- The application has loaded the correct environment variables.
If you're making a guest cart request, check whether the guest cart credential has expired.
Do not substitute the merchant API key for a guest cart credential.
The API Returns 429 Too Many Requests
You've exceeded an applicable request limit.
For management API requests, review the rate limit configured in the Developers dashboard.
Use caching, pagination, and appropriate request backoff.
Respect the Retry-After response header rather than continuously retrying failed requests.
Products Are Not Displaying
Confirm that:
- Your store ID is correct.
- Products have been published.
- Your store contains products.
- The API response contains the expected data.
- Your server-side code is successfully retrieving products.
- The configured cache has revalidated.
The Shopping Cart Disappears After Refreshing
Check whether the cart credential was saved successfully.
Also confirm that your browser is not blocking storage and that the credential hasn't expired.
An expired cart should be replaced with a new cart rather than treated as a valid session.
Payment Methods Are Missing
Ensure you've configured an available payment provider through Shoprivet.
The frontend retrieves configured payment methods dynamically.
If none are available, it cannot offer a valid checkout option.
Checkout Returns an Error
Check the API response for details.
Possible causes include unavailable stock, invalid product variants, missing customer information, unavailable payment methods, or an expired guest cart.
Avoid bypassing server-side validation to force an order through.
Payment Was Completed but the Website Still Shows Unpaid
Check your provider webhook configuration and payment confirmation workflow.
A payment redirect is not proof of payment.
Retrieve the verified order state through the protected order API.
An API Key Accidentally Appears in the Browser
Revoke and replace the exposed key immediately.
Review your environment variable names, Client Component imports, server-to-client props, network requests, and application logs.
Never expose a private merchant API key to an untrusted client.
Production Readiness Checklist
Before accepting real customer orders, verify the following:
Storefront
- [ ] Products load successfully.
- [ ] Product images are optimized.
- [ ] The website works on mobile devices.
- [ ] Search and navigation work.
- [ ] Interactive dialogs support appropriate focus management and keyboard controls.
- [ ] Dedicated error and loading states are implemented.
Shopping Cart
- [ ] Customers can add products.
- [ ] Quantities can be updated.
- [ ] Products can be removed.
- [ ] Guest carts survive ordinary page refreshes.
- [ ] Expired cart credentials are handled correctly.
- [ ] Product variants are validated.
- [ ] Out-of-stock behavior is tested.
Checkout
- [ ] Required customer information is collected.
- [ ] Shipping and tax requirements are implemented.
- [ ] Available payment methods are loaded.
- [ ] Checkout retries reuse their idempotency key.
- [ ] Pending checkout attempts can be recovered after refreshes.
- [ ] Failed and cancelled payments are handled.
- [ ] Provider payment redirects and return routes work.
- [ ] Required provider webhooks are configured.
- [ ] Payments are verified before fulfillment.
Security
- [ ] Merchant API keys remain on the server.
- [ ] Secret credentials are excluded from Git.
- [ ] Customer-facing data is explicitly selected.
- [ ] Guest credentials are not included in URLs or analytics.
- [ ] Order lookup requires the appropriate order access token.
- [ ] Private API responses are not exposed to customers.
Business Operations
- [ ] Orders appear correctly in Shoprivet.
- [ ] Inventory behavior matches store configuration.
- [ ] Payment statuses are accurate.
- [ ] Merchant notifications work as expected.
- [ ] Shipping, return, and refund policies are available.
- [ ] Applicable privacy and business requirements are satisfied.
The starter application in this article provides the foundation.
Complete the relevant production-specific requirements before launching it as a live store.
Frequently Asked Questions
Can I build an ecommerce website with Next.js without developing a backend?
Yes. You can connect a Next.js frontend to a managed headless ecommerce API such as Shoprivet.
The commerce backend already exists, so you don't need to implement the product database, cart persistence, checkout infrastructure, and order management yourself.
Do I need Shopify to build an online store with Next.js?
No.
Shopify is one option, but you can also build a storefront using independent commerce APIs.
Shoprivet provides management and public storefront APIs that can be integrated with your own Next.js application.
Do I need MongoDB or PostgreSQL?
Not for the core commerce functionality demonstrated in this tutorial.
Shoprivet manages the underlying product and order data.
You may still choose to use a separate database for application-specific functionality outside the commerce platform.
Do I need to create Next.js API routes?
Not for the basic integration shown here.
Next.js Server Components can make authenticated server-side requests to the management API.
Client Components can communicate directly with supported public storefront endpoints.
Additional route handlers may be useful for specialized server-side workflows.
Can I use the Shoprivet API key directly in React?
You should not expose a merchant API key in browser-side React code.
Use it from a trusted server environment.
The public storefront API is designed for customer-facing operations without requiring that merchant credential.
Can I design the storefront however I want?
Yes.
When using the API rather than the storefront builder or catalog widget, you control the React components, page layouts, styling, animations, and overall shopping experience.
Your implementation must still follow the supported commerce API contracts.
Can I update products without redeploying my Next.js website?
Yes.
When products are retrieved dynamically from Shoprivet, product changes become available according to your application's fetching and caching strategy.
You don't need to hardcode every product in the React source code.
Can I accept payments through Paystack or Flutterwave?
Shoprivet provides supported payment gateway integrations, including Paystack and Flutterwave.
Availability depends on your merchant eligibility, business location, currency, and configuration.
Can I use Shoprivet for a mobile ecommerce application?
Yes. The API architecture can also be used from a compatible mobile application.
Merchant credentials must remain in a trusted server environment rather than being bundled into a mobile application.
Can I build a custom ecommerce administration dashboard?
Yes.
The management API includes documented endpoints for stores, products, categories, and orders.
A custom administrative application would need appropriate access controls and secure server-side API authentication.
Does Shoprivet support product variants?
Yes.
Product variants are available on eligible Premium and Business plans.
Variants can include different prices, stock quantities, SKUs, and images.
Can I use Shoprivet without its drag-and-drop builder?
Absolutely.
The storefront builder is one way to use the platform.
Developers can also use the REST API to build customer-facing shopping experiences entirely from scratch.
Final Thoughts
A custom ecommerce website doesn't have to come with the responsibility of maintaining a complete ecommerce infrastructure.
You can use the technologies you enjoy working with, such as Next.js, React, TypeScript, and Tailwind CSS, while relying on a managed commerce platform for the underlying transactional functionality.
Throughout this tutorial, we've explored how to:
- Set up a Shoprivet store.
- Create and manage products.
- Generate a merchant API key.
- Securely retrieve product data from Next.js.
- Design a custom fashion storefront.
- Implement a server-managed shopping cart.
- Retrieve payment methods.
- Initiate checkout.
- Manage customer orders.
- Integrate payment verification.
The entire customer-facing experience is yours to design.
The backend commerce operations are handled through Shoprivet.
For developers, freelancers, and agencies, this provides another approach to building custom ecommerce applications without starting every project with a new database schema and payment integration.
Build the storefront you want, without rebuilding the commerce infrastructure behind it.
Create a free Shoprivet account and start building your own custom ecommerce application.
Visit the Developers dashboard after signing in to access API keys, endpoint documentation, JavaScript examples, and public storefront integration instructions.
You can also explore the Shoprivet website or compare available plans.
Disclosure: I'm the developer behind Shoprivet. I built the platform to give businesses and developers an alternative way to create ecommerce experiences without maintaining complex commerce infrastructure. The application in this tutorial is a starter reference implementation. Test the API integration, payment flows, and business-specific requirements before using it in production.
