How to Create Ecommerce in Next.js: Step-by-Step Guide
To create an ecommerce site in
Next.js, build pages for product listing, product details, and a shopping cart using React components and useState or context for state management. Use getStaticProps or getServerSideProps to fetch product data, and add API routes for checkout or payment integration.Syntax
Next.js ecommerce apps use these main parts:
- Pages: React components inside
pages/folder for routes like/productsor/cart. - Data fetching: Use
getStaticPropsto load product data at build time orgetServerSidePropsfor server-side rendering. - State management: Use React
useStateoruseContextto manage cart items. - API routes: Create backend endpoints in
pages/api/for checkout or payment processing.
javascript
export async function getStaticProps() { const products = await fetch('https://fakestoreapi.com/products').then(res => res.json()) return { props: { products } } } export default function ProductsPage({ products }) { return ( <main> <h1>Products</h1> <ul> {products.map(product => ( <li key={product.id}>{product.title} - ${product.price}</li> ))} </ul> </main> ) }
Output
<h1>Products</h1><ul><li>Product 1 - $29.99</li><li>Product 2 - $15.99</li>...</ul>
Example
This example shows a simple ecommerce page with product listing and a cart using React state.
javascript
import { useState } from 'react' export async function getStaticProps() { const products = await fetch('https://fakestoreapi.com/products').then(res => res.json()) return { props: { products } } } export default function Ecommerce({ products }) { const [cart, setCart] = useState([]) function addToCart(product) { setCart(prev => [...prev, product]) } return ( <main> <h1>Simple Ecommerce</h1> <section> <h2>Products</h2> <ul> {products.map(product => ( <li key={product.id}> {product.title} - ${product.price.toFixed(2)} <button onClick={() => addToCart(product)}>Add to Cart</button> </li> ))} </ul> </section> <section> <h2>Cart ({cart.length})</h2> <ul> {cart.map((item, index) => ( <li key={index}>{item.title} - ${item.price.toFixed(2)}</li> ))} </ul> </section> </main> ) }
Output
<h1>Simple Ecommerce</h1><h2>Products</h2><ul><li>Product 1 - $29.99 <button>Add to Cart</button></li>...</ul><h2>Cart (0)</h2><ul></ul>
Common Pitfalls
Common mistakes when building ecommerce in Next.js include:
- Not using
getStaticPropsorgetServerSidePropsfor data fetching, causing slow or broken pages. - Managing cart state only in a single component, losing data on page change.
- Not handling asynchronous API calls properly for checkout.
- Ignoring accessibility and responsive design for product buttons and lists.
Use React Context or libraries like Zustand for persistent cart state, and always test API routes.
javascript
/* Wrong: Cart state lost on page change */ function Cart() { const [cart, setCart] = useState([]) // resets on every page return <div>Cart items: {cart.length}</div> } /* Right: Use Context for cart state */ import { createContext, useContext, useState } from 'react' const CartContext = createContext(null) export function CartProvider({ children }) { const [cart, setCart] = useState([]) return <CartContext.Provider value={{ cart, setCart }}>{children}</CartContext.Provider> } export function useCart() { return useContext(CartContext) }
Quick Reference
Summary tips for Next.js ecommerce:
- Use
getStaticPropsfor fast product pages. - Manage cart state globally with React Context or state libraries.
- Create API routes for secure checkout logic.
- Ensure accessibility and responsive UI for all devices.
- Test payment integration carefully before launch.
Key Takeaways
Use Next.js data fetching methods to load product data efficiently.
Manage shopping cart state globally to keep it across pages.
Create API routes for backend tasks like checkout and payments.
Focus on accessibility and responsive design for better user experience.
Test all parts thoroughly before deploying your ecommerce site.