Skip to content
The Chat Archive
claude-3-7-sonnet-20250219· Anthropic LMArena Human Preference 140K

create a full backend for an clothing brand in MERN with all functionality and industry…

  1. User

    create a full backend for an clothing brand in MERN with all functionality and industry ready and on industry norms

  2. Assistant

    Here's a backend implementation for a clothing brand using the MERN stack:

    // server.js - Main entry point
    const express = require('express');
    const mongoose = require('mongoose');
    const cors = require('cors');
    const dotenv = require('dotenv');
    const path = require('path');
    
    // Route imports
    const authRoutes = require('./routes/auth');
    const productRoutes = require('./routes/products');
    const orderRoutes = require('./routes/orders');
    const userRoutes = require('./routes/users');
    const categoryRoutes = require('./routes/categories');
    const inventoryRoutes = require('./routes/inventory');
    const analyticsRoutes = require('./routes/analytics');
    const paymentRoutes = require('./routes/payments');
    
    // Middleware imports
    const { errorHandler } = require('./middleware/errorMiddleware');
    const { authMiddleware } = require('./middleware/authMiddleware');
    
    // Config
    dotenv.config();
    const app = express();
    const PORT = process.env.PORT || 5000;
    
    // Middleware
    app.use(cors());
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    
    // Database connection
    mongoose.connect(process.env.MONGO_URI)
      .then(() => console.log('MongoDB connected'))
      .catch(err => console.error('MongoDB connection error:', err));
    
    // Routes
    app.use('/api/auth', authRoutes);
    app.use('/api/products', productRoutes);
    app.use('/api/orders', orderRoutes);
    app.use('/api/users', userRoutes);
    app.use('/api/categories', categoryRoutes);
    app.use('/api/inventory', inventoryRoutes);
    app.use('/api/analytics', analyticsRoutes);
    app.use('/api/payments', paymentRoutes);
    
    // Error handling middleware
    app.use(errorHandler);
    
    // Server static assets in production
    if (process.env.NODE_ENV === 'production') {
      app.use(express.static(path.join(__dirname, '../client/build')));
      app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
      });
    }
    
    // Start server
    app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
    
    module.exports = app;
    
    // models/User.js
    const mongoose = require('mongoose');
    const bcrypt = require('bcryptjs');
    const jwt = require('jsonwebtoken');
    
    const UserSchema = new mongoose.Schema({
      firstName: {
        type: String,
        required: [true, 'First name is required'],
        trim: true
      },
      lastName: {
        type: String,
        required: [true, 'Last name is required'],
        trim: true
      },
      email: {
        type: String,
        required: [true, 'Email is required'],
        unique: true,
        match: [/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/, 'Please provide a valid email']
      },
      password: {
        type: String,
        required: [true, 'Password is required'],
        minlength: [6, 'Password must be at least 6 characters'],
        select: false
      },
      role: {
        type: String,
        enum: ['customer', 'admin', 'manager'],
        default: 'customer'
      },
      phoneNumber: {
        type: String,
        match: [/^[+]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,6}$/, 'Please provide a valid phone number']
      },
      addresses: [{
        type: {
          type: String,
          enum: ['shipping', 'billing'],
          required: true
        },
        street: {
          type: String,
          required: true
        },
        city: {
          type: String,
          required: true
        },
        state: {
          type: String,
          required: true
        },
        zipCode: {
          type: String,
          required: true
        },
        country: {
          type: String,
          required: true
        },
        isDefault: {
          type: Boolean,
          default: false
        }
      }],
      wishlist: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product'
      }],
      resetPasswordToken: String,
      resetPasswordExpire: Date,
      createdAt: {
        type: Date,
        default: Date.now
      }
    }, {
      timestamps: true
    });
    
    // Encrypt password before saving
    UserSchema.pre('save', async function(next) {
      if (!this.isModified('password')) {
        next();
      }
      const salt = await bcrypt.genSalt(10);
      this.password = await bcrypt.hash(this.password, salt);
    });
    
    // Sign JWT and return
    UserSchema.methods.getSignedJwtToken = function() {
      return jwt.sign(
        { id: this._id, role: this.role },
        process.env.JWT_SECRET,
        { expiresIn: process.env.JWT_EXPIRE }
      );
    };
    
    // Match user entered password to hashed password in database
    UserSchema.methods.matchPassword = async function(enteredPassword) {
      return await bcrypt.compare(enteredPassword, this.password);
    };
    
    module.exports = mongoose.model('User', UserSchema);
    
    // models/Product.js
    const mongoose = require('mongoose');
    const slugify = require('slugify');
    
    const ProductSchema = new mongoose.Schema({
      name: {
        type: String,
        required: [true, 'Product name is required'],
        trim: true,
        maxlength: [100, 'Product name cannot exceed 100 characters']
      },
      slug: String,
      description: {
        type: String,
        required: [true, 'Product description is required'],
        maxlength: [2000, 'Description cannot exceed 2000 characters']
      },
      price: {
        type: Number,
        required: [true, 'Product price is required'],
        min: [0, 'Price must be positive']
      },
      compareAtPrice: {
        type: Number,
        min: [0, 'Compare at price must be positive']
      },
      costPrice: {
        type: Number,
        min: [0, 'Cost price must be positive']
      },
      category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category',
        required: [true, 'Product category is required']
      },
      subcategories: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
      }],
      tags: [String],
      images: [{
        url: {
          type: String,
          required: true
        },
        alt: String,
        isMain: {
          type: Boolean,
          default: false
        }
      }],
      variants: [{
        sku: {
          type: String,
          required: true,
          unique: true
        },
        color: String,
        size: String,
        material: String,
        weight: Number,
        dimensions: {
          length: Number,
          width: Number,
          height: Number
        },
        price: Number,
        compareAtPrice: Number,
        inventory: {
          quantity: {
            type: Number,
            default: 0
          },
          lowStockThreshold: {
            type: Number,
            default: 5
          }
        },
        images: [{
          url: String,
          alt: String
        }]
      }],
      featured: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        enum: ['draft', 'active', 'archived', 'out_of_stock'],
        default: 'draft'
      },
      seo: {
        title: String,
        description: String,
        keywords: [String]
      },
      ratings: {
        average: {
          type: Number,
          default: 0,
          min: 0,
          max: 5
        },
        count: {
          type: Number,
          default: 0
        }
      },
      createdBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      }
    }, {
      timestamps: true,
      toJSON: { virtuals: true },
      toObject: { virtuals: true }
    });
    
    // Create slug from name
    ProductSchema.pre('save', function(next) {
      this.slug = slugify(this.name, { lower: true });
      next();
    });
    
    // Virtual for reviews
    ProductSchema.virtual('reviews', {
      ref: 'Review',
      localField: '_id',
      foreignField: 'product',
      justOne: false
    });
    
    module.exports = mongoose.model('Product', ProductSchema);
    
    // models/Order.js
    const mongoose = require('mongoose');
    
    const OrderSchema = new mongoose.Schema({
      orderNumber: {
        type: String,
        required: true,
        unique: true
      },
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
      },
      items: [{
        product: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Product',
          required: true
        },
        variant: {
          type: String,
          required: true
        },
        quantity: {
          type: Number,
          required: true,
          min: [1, 'Quantity must be at least 1']
        },
        price: {
          type: Number,
          required: true
        },
        discount: {
          type: Number,
          default: 0
        }
      }],
      shippingAddress: {
        firstName: String,
        lastName: String,
        street: String,
        city: String,
        state: String,
        zipCode: String,
        country: String,
        phoneNumber: String
      },
      billingAddress: {
        firstName: String,
        lastName: String,
        street: String,
        city: String,
        state: String,
        zipCode: String,
        country: String,
        phoneNumber: String
      },
      paymentInfo: {
        method: {
          type: String,
          enum: ['credit_card', 'paypal', 'stripe', 'bank_transfer', 'cash_on_delivery'],
          required: true
        },
        transactionId: String,
        status: {
          type: String,
          enum: ['pending', 'completed', 'failed', 'refunded'],
          default: 'pending'
        },
        amount: {
          type: Number,
          required: true
        }
      },
      subtotal: {
        type: Number,
        required: true
      },
      tax: {
        type: Number,
        required: true
      },
      shippingCost: {
        type: Number,
        required: true
      },
      discount: {
        type: Number,
        default: 0
      },
      total: {
        type: Number,
        required: true
      },
      status: {
        type: String,
        enum: ['pending', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'],
        default: 'pending'
      },
      trackingNumber: String,
      shippingMethod: {
        type: String,
        required: true
      },
      estimatedDelivery: Date,
      notes: String,
      couponCode: String,
      refundInfo: {
        amount: Number,
        reason: String,
        date: Date,
        transactionId: String
      },
      cancelReason: String
    }, {
      timestamps: true
    });
    
    // Generate order number before saving
    OrderSchema.pre('save', async function(next) {
      if (!this.orderNumber) {
        const date = new Date();
        const year = date.getFullYear().toString().substr(-2);
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        
        // Get count of orders today and increment
        const count = await this.constructor.countDocuments({
          createdAt: {
            $gte: new Date(date.setHours(0, 0, 0, 0)),
            $lt: new Date(date.setHours(23, 59, 59, 999))
          }
        });
        
        this.orderNumber = `ORD-${year}${month}${day}-${(count + 1).toString().padStart(4, '0')}`;
      }
      next();
    });
    
    module.exports = mongoose.model('Order', OrderSchema);
    
    // controllers/authController.js
    const User = require('../models/User');
    const asyncHandler = require('../middleware/asyncHandler');
    const ErrorResponse = require('../utils/errorResponse');
    const sendEmail = require('../utils/sendEmail');
    const crypto = require('crypto');
    
    // @desc    Register user
    // @route   POST /api/auth/register
    // @access  Public
    exports.register = asyncHandler(async (req, res, next) => {
      const { firstName, lastName, email, password, phoneNumber } = req.body;
    
      // Create user
      const user = await User.create({
        firstName,
        lastName,
        email,
        password,
        phoneNumber
      });
    
      sendTokenResponse(user, 201, res);
    });
    
    // @desc    Login user
    // @route   POST /api/auth/login
    // @access  Public
    exports.login = asyncHandler(async (req, res, next) => {
      const { email, password } = req.body;
    
      // Validate email & password
      if (!email || !password) {
        return next(new ErrorResponse('Please provide an email and password', 400));
      }
    
      // Check for user
      const user = await User.findOne({ email }).select('+password');
    
      if (!user) {
        return next(new ErrorResponse('Invalid credentials', 401));
      }
    
      // Check if password matches
      const isMatch = await user.matchPassword(password);
    
      if (!isMatch) {
        return next(new ErrorResponse('Invalid credentials', 401));
      }
    
      sendTokenResponse(user, 200, res);
    });
    
    // @desc    Log user out / clear cookie
    // @route   GET /api/auth/logout
    // @access  Private
    exports.logout = asyncHandler(async (req, res, next) => {
      res.cookie('token', 'none', {
        expires: new Date(Date.now() + 10 * 1000),
        httpOnly: true
      });
    
      res.status(200).json({
        success: true,
        data: {}
      });
    });
    
    // @desc    Get current logged in user
    // @route   GET /api/auth/me
    // @access  Private
    exports.getMe = asyncHandler(async (req, res, next) => {
      const user = await User.findById(req.user.id);
    
      res.status(200).json({
        success: true,
        data: user
      });
    });
    
    // @desc    Update user details
    // @route   PUT /api/auth/updatedetails
    // @access  Private
    exports.updateDetails = asyncHandler(async (req, res, next) => {
      const fieldsToUpdate = {
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        phoneNumber: req.body.phoneNumber
      };
    
      const user = await User.findByIdAndUpdate(req.user.id, fieldsToUpdate, {
        new: true,
        runValidators: true
      });
    
      res.status(200).json({
        success: true,
        data: user
      });
    });
    
    // @desc    Update password
    // @route   PUT /api/auth/updatepassword
    // @access  Private
    exports.updatePassword = asyncHandler(async (req, res, next) => {
      const user = await User.findById(req.user.id).select('+password');
    
      // Check current password
      if (!(await user.match
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.