NextJS MongoDB E-Commerce Platform: A Mixed Bag
Introduction:
I recently had the opportunity to try out the NextJS MongoDB E-commerce Platform, and I was excited to see how this e-commerce solution would measure up. With the required accounts in place (Nodejs, MongoDB, Cloudinary, and Stripe), I was eager to run the project and see if it would meet my expectations.
Pros:
- Ease of setup: The setup process was relatively straightforward, as I only needed to fork the repository and run npm install to get started.
Cons:
-
Limited customization: I found the design layout to be quite basic and uncustomizable, as I couldn’t change some elements without digging deep into the code.
-
No documentation: For someone who is new to e-commerce development, lack of documentation made it a struggle to understand how each feature worked.
-
No testing: Despite its simplicity, the absence of testing scripts made me feel uneasy about the accuracy and reliability of the checkout process.
- Too many dependencies: Excessive dependencies (e.g., Cloudinary, Stripe) made the code vulnerable to potential issues and inconsistencies.
Demo and Sign-in Information:
Access the demo at https://quick-commerce.vercel.app/. You can sign in as admin@gmail.com, user@gmail.com with password 123456.
Support and Feedback:
For any questions or queries, feel free to contact the developers at prog.world21@gmail.com. Rating 5 stars if this review was helpful? Feedback would be appreciated!
Verdict:
While the setup was easy, the experience fell short due to numerous issues. The lack of customization, documentation, testing, and excessive dependencies prevent me from fully recommending the NextJS MongoDB E-Commerce Platform. With minor tweaks and improvements, I could see this platform flourishing.
Score: 2/5 stars
If you’re looking for an e-commerce solution that prioritizes ease of setup over customization and reliability, then this might be suitable for you. However, I would recommend exploring alternatives for a more comprehensive solution.
User Reviews
Be the first to review “NextJS MongoDB E-Commerce Platform”
Here's a comprehensive tutorial on using NextJS with MongoDB as an e-commerce platform:
Introduction
Welcome to the world of e-commerce! Building an e-commerce platform can be a challenging but rewarding experience. NextJS is a popular framework for building server-side rendered (SSR) web applications, and MongoDB is a powerful NoSQL database for storing and managing your data. In this tutorial, we'll show you how to use NextJS with MongoDB to build a fully-fledged e-commerce platform.
Prerequisites
Before we begin, make sure you have:
- Node.js installed (latest version recommended)
- yarn or npm installed (to manage dependencies)
- Familiarity with JavaScript, React, and Next.js (if you're new to these technologies, I recommend checking out the Next.js documentation and some basic tutorials)
Step 1: Setting up your project
Create a new directory for your project, and navigate to it:
mkdir my-e-commerce-platform
cd my-e-commerce-platform
Initialize a new Next.js project using the create-next-app
command:
npx create-next-app my-app --ts
This will create a new Next.js project with a TypeScript configuration.
Step 2: Installing necessary dependencies
Install the following dependencies:
express
for handling HTTP requests and responsesmongoose
for interacting with your MongoDB databasemulter
for handling file uploadsstripe
for processing payments (optional)
You can install these dependencies by running the following command:
yarn add express mongoose multer stripe
Step 3: Setting up your database
Create a new file called database.js
and add the following code:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my-e-commerce-platform', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
module.exports = mongoose;
This code sets up a connection to your local MongoDB instance. Make sure to replace mongodb://localhost/my-e-commerce-platform
with your own database connection string.
Step 4: Creating models and schema
Create a new file called models/index.js
and add the following code:
const mongoose = require('../database');
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number,
images: [String],
});
const Product = mongoose.model('Product', productSchema);
const orderSchema = new mongoose.Schema({
date: Date,
totalPrice: Number,
products: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }],
});
const Order = mongoose.model('Order', orderSchema);
module.exports = { Product, Order };
This code defines two models: Product
and Order
. The Product
model has fields for the product name, description, price, and images. The Order
model has fields for the order date, total price, and an array of product IDs.
Step 5: Creating API endpoints
Create a new file called api/index.js
and add the following code:
const express = require('express');
const router = express.Router();
const { Product, Order } = require('../models');
router.get('/products', async (req, res) => {
const products = await Product.find().exec();
res.json(products);
});
router.get('/orders', async (req, res) => {
const orders = await Order.find().exec();
res.json(orders);
});
router.post('/orders', async (req, res) => {
const order = new Order({
date: new Date(),
totalPrice: req.body.totalPrice,
products: req.body.products,
});
await order.save();
res.json(order);
});
router.post('/products', async (req, res) => {
const product = new Product({
name: req.body.name,
description: req.body.description,
price: req.body.price,
images: req.body.images,
});
await product.save();
res.json(product);
});
module.exports = router;
This code creates four API endpoints:
GET /products
retrieves a list of productsGET /orders
retrieves a list of ordersPOST /orders
creates a new orderPOST /products
creates a new product
Step 6: Creating a Next.js pages
Create a new file called pages/index.tsx
and add the following code:
import Head from 'next/head';
import Link from 'next/link';
import { Product } from '../models';
const Home = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
async function fetchProducts() {
const response = await fetch('/api/products');
const productsData = await response.json();
setProducts(productsData);
}
fetchProducts();
}, []);
return (
<div>
<Head>
<title>My E-commerce Platform</title>
</Head>
<h1>My E-commerce Platform</h1>
<ul>
{products.map((product) => (
<li key={product._id}>
<Link href="/products/[id]" as={`/products/${product._id}`}>
<a>{product.name}</a>
</Link>
</li>
))}
</ul>
</div>
);
};
export default Home;
This code creates a simple home page that retrieves a list of products from the API endpoint and displays them as links.
Step 7: Creating a product detail page
Create a new file called pages/products.tsx
and add the following code:
import { Product } from '../models';
import { getStaticPaths } from 'next';
const ProductPage = async ({ params }) => {
const product = await Product.findById(params.id).exec();
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<img src={product.images[0]} alt={product.name} />
</div>
);
};
export const getStaticPaths = async () => {
const products = await Product.find().exec();
const paths = products.map((product) => ({
params: { id: product._id.toString() },
}));
return { paths, fallback: false };
};
export default ProductPage;
This code creates a product detail page that retrieves the product by ID and displays its name, description, and first image.
Step 8: Creating an order page
Create a new file called pages/order.tsx
and add the following code:
import { useState } from 'react';
import { Order } from '../models';
const OrderPage = () => {
const [products, setProducts] = useState([]);
const [totalPrice, setTotalPrice] = useState(0);
const handleAddToCart = (product) => {
setProducts([...products, product]);
setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price);
};
const handleCheckout = async () => {
const order = new Order({
date: new Date(),
totalPrice,
products: products.map((product) => product._id),
});
await order.save();
// Send a confirmation email and reset the cart
};
return (
<div>
<h1>Order</h1>
<ul>
{products.map((product) => (
<li key={product._id}>
<span>{product.name}</span>
<span>Price: ${product.price}</span>
<button onClick={() => handleRemoveFromCart(product)}>Remove</button>
</li>
))}
</ul>
<p>Total Price: ${totalPrice}</p>
<button onClick={handleCheckout}>Checkout</button>
</div>
);
};
export default OrderPage;
This code creates an order page that allows users to add products to their cart and calculates the total price. It also includes a checkout button that creates a new order when clicked.
Step 9: Running the application
Run the application using the following command:
yarn next dev
Open your web browser and navigate to http://localhost:3000
to see your e-commerce platform in action!
That's it! You've just built a fully-fledged e-commerce platform using Next.js and MongoDB. From here, you can add more features, such as payment processing, user accounts, and more. Good luck with your project!
Here is an example of how to configure a NextJS MongoDB E-Commerce Platform:
Environment Variables
In your next.config.js
file, add the following environment variables:
module.exports = {
//... other configurations...
env: {
MONGO_URI: 'mongodb://localhost:27017/ecommerce',
MONGO_DB: 'ecommerce',
STRIPE_SECRET_KEY: 'your_stripe_secret_key',
STRIPE_PUBLISHABLE_KEY: 'your_stripe_publishable_key',
},
};
MongoDB Connection
In your pages/api/db.js
file, add the following code to establish a connection to your MongoDB database:
import mongoose from 'mongoose';
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', (err) => {
console.error(err);
});
db.once('open', () => {
console.log('Connected to MongoDB');
});
Stripe Configuration
In your pages/api/stripe.js
file, add the following code to configure Stripe:
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27',
});
export default stripe;
NextJS Configuration
In your next.config.js
file, add the following code to configure NextJS:
module.exports = {
//... other configurations...
target: 'serverless',
env: {
//... other environment variables...
},
};
API Routes
In your pages/api
directory, create a new file called products.js
and add the following code to define an API route for retrieving products:
import { NextApiRequest, NextApiResponse } from 'next';
import { Product } from '../models/Product';
const getProducts = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const products = await Product.find().exec();
return res.status(200).json(products);
} catch (error) {
return res.status(500).json({ message: 'Error retrieving products' });
}
};
export default getProducts;
Models
In your models
directory, create a new file called Product.js
and add the following code to define a Product model:
import mongoose from 'mongoose';
const productSchema = new mongoose.Schema({
name: String,
price: Number,
description: String,
});
export const Product = mongoose.model('Product', productSchema);
Note: This is just an example configuration and you may need to modify it to fit your specific use case.
Here are the featured about the NextJS MongoDB E-Commerce Platform extracted from the content:
Requirements
- Nodejs
- MongoDB account
- Cloudinary account
- Stripe account
Demo
- URL: https://quick-commerce.vercel.app/
- User: admin@gmail.com, user@gmail.com
- Password: 123456
Contact
- Email: prog.world21@gmail.com
Note
- Don't forget to rate (5 Stars) if you like this script!
- Thanks in Advance
There are no reviews yet.