Imagine owning an e-commerce store that loads blazingly fast, ranks high on search engines, and offers a seamless shopping experience—all built with cutting-edge technology. With Next.js, this dream is not only achievable but surprisingly straightforward. Let’s dive into creating your custom e-commerce store using Next.js!
Why Choose Next.js for Your E-Commerce Store?
Next.js is a powerful React framework that brings the best of server-side rendering (SSR) and static site generation (SSG). Here’s why it’s perfect for e-commerce:
SEO Optimization: Server-side rendering ensures your product pages are search-engine friendly.
Fast Performance: Next.js pre-renders pages, improving load times.
Scalability: Easily handles dynamic content with API routes and incremental static regeneration.
Built-In Routing: No need for a third-party library to manage navigation.
Step 1: Setting Up the Project
Start by creating a new Next.js project:
npx create-next-app@latest my-ecommerce-store --typescript
cd my-ecommerce-store
npm install
Step 2: Structuring Your E-Commerce Store
Here’s a basic folder structure for your store:
my-ecommerce-store/
├── components/ # Reusable UI components (Navbar, Footer, ProductCard)
├── pages/ # Routes for your store (Home, Product, Cart)
│ ├── index.tsx # Homepage
│ ├── product/ # Dynamic product pages
│ ├── cart.tsx # Shopping cart
├── public/ # Static assets (images, icons)
├── styles/ # CSS/SCSS modules for styling
Step 3: Creating the Homepage
The homepage should display featured products and categories.
Example:
import ProductCard from "../components/ProductCard";
export default function Home() {
const products = [
{ id: 1, name: "Product A", price: "$25", image: "/product-a.jpg" },
{ id: 2, name: "Product B", price: "$40", image: "/product-b.jpg" },
];
return (
<div>
<h1>Welcome to My Store</h1>
<div className="product-grid">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
</div>
);
}
Step 4: Building a Dynamic Product Page
Next.js makes it easy to create dynamic routes.
Create a [id].tsx file in the pages/product/ folder.
Use getStaticPaths and getStaticProps to pre-render product pages.
Example:
import { GetStaticPaths, GetStaticProps } from "next";
export default function ProductPage({ product }: { product: any }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>Price: {product.price}</p>
</div>
);
}
export const getStaticPaths: GetStaticPaths = async () => {
const res = await fetch("https://api.example.com/products");
const products = await res.json();
const paths = products.map((product: any) => ({
params: { id: product.id.toString() },
}));
return { paths, fallback: false };
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
const res = await fetch(`https://api.example.com/products/${params?.id}`);
const product = await res.json();
return { props: { product } };
};
Step 5: Implementing the Shopping Cart
Create a CartContext to manage cart state across the application.
CartContext Example:
import { createContext, useState, useContext } from "react";
const CartContext = createContext([]);
export const useCart = () => useContext(CartContext);
export const CartProvider = ({ children }: { children: React.ReactNode }) => {
const [cart, setCart] = useState([]);
const addToCart = (product: any) => {
setCart([...cart, product]);
};
return (
<CartContext.Provider value={{ cart, addToCart }}>
{children}
</CartContext.Provider>
);
};
Wrap your app in CartProvider in _app.tsx:
import { CartProvider } from "../context/CartContext";
export default function MyApp({ Component, pageProps }: any) {
return (
<CartProvider>
<Component {...pageProps} />
</CartProvider>
);
}
Step 6: Adding Payment Integration
Integrate a payment gateway like Stripe or Paystack for secure transactions.
Stripe Checkout Example:
import { loadStripe } from "@stripe/stripe-js";
const stripePromise = loadStripe("your-stripe-public-key");
const handleCheckout = async () => {
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({
lineItems: [{ price: "price_id", quantity: 1 }],
mode: "payment",
successUrl: "https://yourstore.com/success",
cancelUrl: "https://yourstore.com/cancel",
});
if (error) console.error(error);
};
Step 7: Deploying Your Store
Once your store is ready, deploy it using Vercel, the official Next.js deployment platform.
Steps:
Push your code to GitHub.
Go to Vercel and import your repository.
Configure your environment variables (e.g., API keys).
Deploy with a single click!
Conclusion
By following this guide, you’ve built a custom e-commerce store with Next.js that is fast, SEO-friendly, and scalable. Now, focus on enhancing the user experience with features like search, filters, and product reviews.
Top comments (0)