Integration Guide · Next.js

Build an Online Store with Next.js

Render SEO-friendly product pages in Next.js App Router while Shoprivet manages inventory, guest carts, checkout, digital file delivery, and payment verification.

Target: Next.js (App Router) Integration: Public Storefront REST API + Server-side /v1 Management API OpenAPI 3.0 Spec

Prerequisites & Setup Checklist

  • Next.js 14+ or 15+ (App Router)
  • Node.js 20+
  • A Shoprivet account and store slug
  • Sign up at shoprivet.io/app/signup, create a store, add products, and configure a payment gateway (or Cash on delivery).

Environment Variables

Variable Example Value Exposure Rule
SHOPRIVET_API_URL https://api.shoprivet.io Server (or safe public URL)
SHOPRIVET_STORE_SLUG downtown-shop Public store slug
SHOPRIVET_API_KEY shoprivet_live_example_key Server ONLY (never use NEXT_PUBLIC_)

Implementation Steps

1. Create store, products, and payments in Shoprivet

Create a store in the Shoprivet dashboard (or via POST /v1/stores from a script), publish at least one product, and connect Stripe, Paystack, Flutterwave, Razorpay, PayPal, or leave Cash on delivery enabled.

2. Configure environment variables safely

Put your store slug in a non-secret config variable and keep SHOPRIVET_API_KEY strictly on the server inside .env.local. Never prefix a merchant API key with NEXT_PUBLIC_ because Next.js inlines NEXT_PUBLIC_ variables into browser JavaScript bundles.

3. Fetch products inside a Next.js Server Component

Public storefront routes require no API key and keep product prices and stock accurate in initial server-rendered HTML for Google and AI crawlers.

app/store/page.tsx · Server Component product catalog fetch
const API_BASE = process.env.SHOPRIVET_API_URL ?? 'https://api.shoprivet.io';
const STORE_SLUG = process.env.SHOPRIVET_STORE_SLUG ?? 'downtown-shop';

export const revalidate = 60;

export default async function StorePage() {
  const res = await fetch(`${API_BASE}/public/stores/${STORE_SLUG}/products?page=1&limit=24`, {
    next: { revalidate: 60 },
  });
  if (!res.ok) throw new Error('Unable to load Shoprivet catalog');
  const data = await res.json();

  return (
    <main>
      <h1>Store Catalog</h1>
      <ul>
        {data.products.map((product: any) => (
          <li key={product.id}>
            <strong>{product.name}</strong> - {product.price} {product.currency.toUpperCase()}
          </li>
        ))}
      </ul>
    </main>
  );
}
lib/shoprivet-cart.ts · Browser cart, checkout, and payment confirmation
const API_BASE = 'https://api.shoprivet.io';
const SLUG = 'downtown-shop';

export async function createCart() {
  const res = await fetch(`${API_BASE}/public/stores/${SLUG}/carts`, {
    method: 'POST',
    credentials: 'omit',
  });
  if (!res.ok) throw new Error('Could not initialize cart');
  return res.json(); // { credential, cart }
}

export async function addToCart(credential: string, productId: string, quantity = 1) {
  const res = await fetch(`${API_BASE}/public/stores/${SLUG}/carts/current/items`, {
    method: 'POST',
    credentials: 'omit',
    headers: { Authorization: `Bearer ${credential}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ productId, quantity }),
  });
  if (!res.ok) throw new Error('Unable to add item to cart');
  return res.json();
}

export async function startCheckout(credential: string, customer: { name: string; email: string; provider: string }) {
  const res = await fetch(`${API_BASE}/public/stores/${SLUG}/carts/current/checkout`, {
    method: 'POST',
    credentials: 'omit',
    headers: { Authorization: `Bearer ${credential}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      ...customer,
      idempotencyKey: crypto.randomUUID(),
    }),
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.message || 'Checkout failed');
  // Persist data.orderAccessToken in sessionStorage for /order-confirmed lookup
  if (data.authorizationUrl) window.location.assign(data.authorizationUrl);
  return data;
}
app/api/merchant/orders/route.ts · Optional Route Handler for server-only /v1 calls
import { NextResponse } from 'next/server';

export async function GET() {
  const apiKey = process.env.SHOPRIVET_API_KEY;
  const storeId = process.env.SHOPRIVET_STORE_ID;
  if (!apiKey || !storeId) {
    return NextResponse.json({ error: 'Server credentials not configured' }, { status: 500 });
  }

  const upstream = await fetch(`https://api.shoprivet.io/v1/stores/${storeId}/orders?page=1&limit=20`, {
    headers: { Authorization: `Bearer ${apiKey}` },
    cache: 'no-store',
  });

  const payload = await upstream.json();
  return NextResponse.json(payload, { status: upstream.status });
}

Payment Verification, Error Handling & Security

After the payment gateway returns the buyer to your Next.js confirmation route, read the stored orderNumber and orderAccessToken and call POST /public/stores/:slug/orders/:orderNumber/confirm before showing paid order confirmation or digital downloads.

  • Keep SHOPRIVET_API_KEY strictly in server components, route handlers, or server actions.
  • Re-use the same idempotencyKey when retrying the exact same checkout form submission so double-clicks do not create duplicate orders.
  • Verify stock and totals from Shoprivet cart responses rather than trusting client-supplied item prices.

Deployment

Deploy on Vercel, Netlify, Fly.io, or Node containers. Add SHOPRIVET_API_KEY and SHOPRIVET_STORE_ID to your hosting provider secret manager without NEXT_PUBLIC_ prefixes.