DEV Community

Cover image for How to Create a Custom E-Commerce Store Using Next.js
Raji moshood
Raji moshood

Posted on

1

How to Create a Custom E-Commerce Store Using Next.js

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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>
    );
}

Enter fullscreen mode Exit fullscreen mode

Step 4: Building a Dynamic Product Page

Next.js makes it easy to create dynamic routes.

  1. Create a [id].tsx file in the pages/product/ folder.

  2. 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 } };
};

Enter fullscreen mode Exit fullscreen mode

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>
    );
};
Enter fullscreen mode Exit fullscreen mode

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>
    );
}

Enter fullscreen mode Exit fullscreen mode

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);
};

Enter fullscreen mode Exit fullscreen mode

Step 7: Deploying Your Store

Once your store is ready, deploy it using Vercel, the official Next.js deployment platform.

Steps:

  1. Push your code to GitHub.

  2. Go to Vercel and import your repository.

  3. Configure your environment variables (e.g., API keys).

  4. 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.

NextJS #ECommerceDevelopment #WebDevelopment #ReactJS #FullStackDeveloper #CodingTutorial #BuildWithNextJS

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed: Zero in on just the tests that failed in your previous run
  • 2:34 --only-changed: Test only the spec files you've modified in git
  • 4:27 --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • 5:15 --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • 5:51 --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay