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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!