From Zero to Storefront: My Journey Building an E-commerce Site

aelassas

aelassas

Posted on November 7, 2024

From Zero to Storefront: My Journey Building an E-commerce Site

Contents

  1. Introduction
  2. Tech Stack
  3. Quick Overview
  4. API
  5. Frontend
  6. Admin Dashboard
  7. Resources

Source code: https://github.com/aelassas/wexcommerce

Demo: https://wexcommerce.dynv6.net:8002

Introduction

For developers who value creative freedom and technical control, traditional eCommerce platforms like Shopify can feel restrictive. While Shopify's templates offer quick setup, and their Storefront API provides some flexibility, neither solution delivers the complete architectural freedom that modern developers crave.

The idea emerged from a desire to build without boundaries – a fully customizable eCommerce site where every aspect is within your control:

  • Own the UI/UX: Design unique customer experiences without fighting against template limitations
  • Control the Backend: Implement custom business logic and data structures that perfectly match the requirements
  • Master DevOps: Deploy, scale, and monitor the application with preferred tools and workflows
  • Extend Freely: Add new features and integrations without platform constraints or additional fees

Tech Stack

Here's the tech stack that made it possible:

  • Node.js
  • Next.js
  • MongoDB
  • MUI
  • TypeScript
  • Stripe
  • Docker

A key design decision was made to use TypeScript due to its numerous advantages. TypeScript offers strong typing, tooling, and integration, resulting in high-quality, scalable, more readable and maintainable code that is easy to debug and test.

I chose Next.js for its powerful rendering capabilities, MongoDB for flexible data modeling, and Stripe for secure payment processing.

By choosing this stack, you're not just building a store – you're investing in a foundation that can evolve with your needs, backed by robust open-source technologies and a growing developer community.

Building a site with Next.js provides a solid foundation for scaling a business. Focus on performance, security, and user experience while maintaining code quality and documentation. Regular updates and monitoring will ensure the platform remains competitive and reliable.

Next.js stands out as an excellent choice due to its:

  • Superior Performance: Built-in optimizations for fast page loads and seamless user experiences
  • SEO Advantages: Server-side rendering capabilities that ensure your products are discoverable
  • Scalability: Enterprise-ready architecture that grows with your business
  • Rich Ecosystem: Vast collection of libraries and tools for rapid development
  • Developer Experience: Intuitive development workflow with hot reloading and automatic routing

Quick overview

Frontend

From the frontend, the user can search for available products, add products to cart and checkout.

Below is the landing page of the frontend:

Frontend

Below is the search page of the frontend:

Frontend

Below is a sample product page:

Frontend

Below is a fullscreen view of product images:

Frontend

Below is cart page:

Frontend

Below is checkout page:

Frontend

Below is the sign in page:

Frontend

Below is the sign up page:

Frontend

Below is the page where the user can see his orders:

Frontend

That's it! Those are the main pages of the frontend.

Admin Dashboard

From the admin dashboard, admins can manage categories, products, users and orders.

Admins can also manage the following settings:

  • Locale Settings: Language of the platform (English or French) and currency
  • Delivery Settings: Delivery methods enabled and the cost of each one
  • Payment Settings: Payment methods enabled (Credit card, Cash on delivery or Wire transfer)
  • Bank Settings: Bank information for wire transfer (IBAN and other info)

Below is the sign in page:

Backend

Below is the dashboard page from which admins can see and manage orders:

Backend

Below is the page from which admins manage categories:

Backend

Below is the page from which admins can see and manage products:

Backend

Below is the page from which admins edit products:

Backend

Below is a fullscreen view of product images:

Backend

Below is settings page:

Backend

That's it. Those are the main pages of the admin dashboard.

API

api

The api is a Node.js server application that exposes a RESTful API using Express which gives access to MongoDB database.

The api is used by the frontend, the admin dashboard and will be used by the mobile app as well.

The api exposes all functions needed for the admin dashboard and the frontend. The api follows the MVC design pattern. JWT is used for authentication. There are some functions that need authentication such as functions related to managing products and orders, and others that do not need authentication such as retrieving categories and available products for non authenticated users:

  • ./api/src/models/ folder contains MongoDB models.
  • ./api/src/routes/ folder contains Express routes.
  • ./api/src/controllers/ folder contains controllers.
  • ./api/src/middlewares/ folder contains middlewares.
  • ./api/src/app.ts is the main server where routes are loaded.
  • ./api/src/index.ts is the main entry point of the api.

index.ts is in the main server:

import 'dotenv/config'
import process from 'node:process'
import fs from 'node:fs/promises'
import http from 'node:http'
import https, { ServerOptions } from 'node:https'
import * as env from './config/env.config'
import * as databaseHelper from './common/databaseHelper'
import app from './app'
import * as logger from './common/logger'

if (
  await databaseHelper.connect(env.DB_URI, env.DB_SSL, env.DB_DEBUG)
  && await databaseHelper.initialize()
) {
  let server: http.Server | https.Server

  if (env.HTTPS) {
    https.globalAgent.maxSockets = Number.POSITIVE_INFINITY
    const privateKey = await fs.readFile(env.PRIVATE_KEY, 'utf8')
    const certificate = await fs.readFile(env.CERTIFICATE, 'utf8')
    const credentials: ServerOptions = { key: privateKey, cert: certificate }
    server = https.createServer(credentials, app)

    server.listen(env.PORT, () => {
      logger.info('HTTPS server is running on Port', env.PORT)
    })
  } else {
    server = app.listen(env.PORT, () => {
      logger.info('HTTP server is running on Port', env.PORT)
    })
  }

  const close = () => {
    logger.info('Gracefully stopping...')
    server.close(async () => {
      logger.info(`HTTP${env.HTTPS ? 'S' : ''} server closed`)
      await databaseHelper.close(true)
      logger.info('MongoDB connection closed')
      process.exit(0)
    })
  }

  ['SIGINT', 'SIGTERM', 'SIGQUIT'].forEach((signal) => process.on(signal, close))
}
Enter fullscreen mode Exit fullscreen mode

This is a TypeScript file that starts a server using Node.js and Express. It imports several modules including dotenv, process, fs, http, https, mongoose, and app. It then establishes a connection with MongoDB database. It then checks if the HTTPS environment variable is set to true, and if so, creates an HTTPS server using the https module and the provided private key and certificate. Otherwise, it creates an HTTP server using the http module. The server listens on the port specified in the PORT environment variable.

The close function is defined to gracefully stop the server when a termination signal is received. It closes the server and the MongoDB connection, and then exits the process with a status code of 0. Finally, it registers the close function to be called when the process receives a SIGINT, SIGTERM, or SIGQUIT signal.

app.ts is the main entry point of the api:

import express from 'express'
import compression from 'compression'
import helmet from 'helmet'
import nocache from 'nocache'
import cookieParser from 'cookie-parser'
import i18n from './lang/i18n'
import * as env from './config/env.config'
import cors from './middlewares/cors'
import allowedMethods from './middlewares/allowedMethods'
import userRoutes from './routes/userRoutes'
import categoryRoutes from './routes/categoryRoutes'
import productRoutes from './routes/productRoutes'
import cartRoutes from './routes/cartRoutes'
import orderRoutes from './routes/orderRoutes'
import notificationRoutes from './routes/notificationRoutes'
import deliveryTypeRoutes from './routes/deliveryTypeRoutes'
import paymentTypeRoutes from './routes/paymentTypeRoutes'
import settingRoutes from './routes/settingRoutes'
import stripeRoutes from './routes/stripeRoutes'
import wishlistRoutes from './routes/wishlistRoutes'
import * as helper from './common/helper'

const app = express()

app.use(helmet.contentSecurityPolicy())
app.use(helmet.dnsPrefetchControl())
app.use(helmet.crossOriginEmbedderPolicy())
app.use(helmet.frameguard())
app.use(helmet.hidePoweredBy())
app.use(helmet.hsts())
app.use(helmet.ieNoOpen())
app.use(helmet.noSniff())
app.use(helmet.permittedCrossDomainPolicies())
app.use(helmet.referrerPolicy())
app.use(helmet.xssFilter())
app.use(helmet.originAgentCluster())
app.use(helmet.crossOriginResourcePolicy({ policy: 'cross-origin' }))
app.use(helmet.crossOriginOpenerPolicy())

app.use(nocache())
app.use(compression({ threshold: 0 }))
app.use(express.urlencoded({ limit: '50mb', extended: true }))
app.use(express.json({ limit: '50mb' }))

app.use(cors())
app.options('*', cors())
app.use(cookieParser(env.COOKIE_SECRET))
app.use(allowedMethods)

app.use('/', userRoutes)
app.use('/', categoryRoutes)
app.use('/', productRoutes)
app.use('/', cartRoutes)
app.use('/', orderRoutes)
app.use('/', notificationRoutes)
app.use('/', deliveryTypeRoutes)
app.use('/', paymentTypeRoutes)
app.use('/', settingRoutes)
app.use('/', stripeRoutes)
app.use('/', wishlistRoutes)

i18n.locale = env.DEFAULT_LANGUAGE

await helper.mkdir(env.CDN_USERS)
await helper.mkdir(env.CDN_TEMP_USERS)
await helper.mkdir(env.CDN_CATEGORIES)
await helper.mkdir(env.CDN_TEMP_CATEGORIES)
await helper.mkdir(env.CDN_PRODUCTS)
await helper.mkdir(env.CDN_TEMP_PRODUCTS)

export default app
Enter fullscreen mode Exit fullscreen mode

First of all, we create an Express app and load middlewares such as cors, compression, helmet, and nocache. We set up various security measures using the helmet middleware library. We also import various route files for different parts of the application such as productRoutes, orderRoutes, categoryRoutes, notificationRoutes, userRoutes. Finally, we load Express routes and export app.

There are 11 routes in the api. Each route has its own controller following the MVC design pattern and SOLID principles. Below are the main routes:

  • userRoutes: Provides REST functions related to users
  • categoryRoutes: Provides REST functions related to categories
  • productRoutes: Provides REST functions related to products
  • cartRoutes: Provides REST functions related to carts
  • wishlistRoutes: Provides REST functions related to wishlists
  • deliveryTypeRoutes: Provides REST functions related to delivery methods
  • paymentTypeRoutes: Provides REST functions related to payment methods
  • orderRoutes: Provides REST functions related to orders
  • notificationRoutes: Provides REST functions related to notifications
  • settingRoutes: Provides REST functions related to settings
  • stripeRoutes: Provides REST functions related to Stripe payment gateway

We are not going to explain each route one by one. We'll take, for example, categoryRoutes and see how it was made:

import express from 'express'
import multer from 'multer'
import routeNames from '../config/categoryRoutes.config'
import authJwt from '../middlewares/authJwt'
import * as categoryController from '../controllers/categoryController'

const routes = express.Router()

routes.route(routeNames.validate).post(authJwt.verifyToken, categoryController.validate)
routes.route(routeNames.checkCategory).get(authJwt.verifyToken, categoryController.checkCategory)
routes.route(routeNames.create).post(authJwt.verifyToken, categoryController.create)
routes.route(routeNames.update).put(authJwt.verifyToken, categoryController.update)
routes.route(routeNames.delete).delete(authJwt.verifyToken, categoryController.deleteCategory)
routes.route(routeNames.getCategory).get(authJwt.verifyToken, categoryController.getCategory)
routes.route(routeNames.getCategories).get(categoryController.getCategories)
routes.route(routeNames.getFeaturedCategories).get(categoryController.getFeaturedCategories)
routes.route(routeNames.searchCategories).get(authJwt.verifyToken, categoryController.searchCategories)
routes.route(routeNames.createImage).post([authJwt.verifyToken, multer({ storage: multer.memoryStorage() }).single('image')], categoryController.createImage)
routes.route(routeNames.updateImage).post([authJwt.verifyToken, multer({ storage: multer.memoryStorage() }).single('image')], categoryController.updateImage)
routes.route(routeNames.deleteImage).post(authJwt.verifyToken, categoryController.deleteImage)
routes.route(routeNames.deleteTempImage).post(authJwt.verifyToken, categoryController.deleteTempImage)

export default routes
Enter fullscreen mode Exit fullscreen mode

First of all, we create an Express Router. Then, we create routes using its name, its method, middlewares and its controller.

routeNames contains categoryRoutes route names:

export default {
    validate: '/api/validate-category',
    checkCategory: '/api/check-category/:id',
    create: '/api/create-category',
    update: '/api/update-category/:id',
    delete: '/api/delete-category/:id',
    getCategory: '/api/category/:id/:language',
    getCategories: '/api/categories/:language/:imageRequired',
    getFeaturedCategories: '/api/featured-categories/:language/:size',
    searchCategories: '/api/search-categories/:language',
    createImage: '/api/create-category-image',
    updateImage: '/api/update-category-image/:id',
    deleteImage: '/api/delete-category-image/:id',
    deleteTempImage: '/api/delete-temp-category-image/:image',
}
Enter fullscreen mode Exit fullscreen mode

categoryController contains the main business logic regarding categories. We are not going to see all the source code of the controller since it's quite large but we'll take create controller function for example.

Below is Category model:

import { Schema, model } from 'mongoose'
import * as env from '../config/env.config'

const categorySchema = new Schema<env.Category>({
  values: {
    type: [Schema.Types.ObjectId],
    ref: 'Value',
    validate: (value: any) => Array.isArray(value),
  },
  image: {
    type: String,
  },
  featured: {
    type: Boolean,
    default: false,
  },
}, {
  timestamps: true,
  strict: true,
  collection: 'Category',
})

const Category = model<env.Category>('Category', categorySchema)

export default Category
Enter fullscreen mode Exit fullscreen mode

A Category has multiple values. One value per language. By default, English and French languages are supported.

Below is Value model:

import { Schema, model } from 'mongoose'
import * as env from '../config/env.config'

const locationValueSchema = new Schema<env.Value>(
  {
    language: {
      type: String,
      required: [true, "can't be blank"],
      index: true,
      trim: true,
      lowercase: true,
      minLength: 2,
      maxLength: 2,
    },
    value: {
      type: String,
      required: [true, "can't be blank"],
      index: true,
      trim: true,
    },
  },
  {
    timestamps: true,
    strict: true,
    collection: 'Value',
  },
)

const Value = model<env.Value>('Value', locationValueSchema)

export default Value
Enter fullscreen mode Exit fullscreen mode

A Value has a language code (ISO 639-1) and a string value.

Below is create controller function:

export const create = async (req: Request, res: Response) => {
  const { body }: { body: wexcommerceTypes.UpsertCategoryPayload } = req
  const { values, image, featured } = body

  try {
    if (image) {
      const _image = path.join(env.CDN_TEMP_CATEGORIES, image)

      if (!await helper.exists(_image)) {
        logger.error(i18n.t('CATEGORY_IMAGE_NOT_FOUND'), body)
        return res.status(400).send(i18n.t('CATEGORY_IMAGE_NOT_FOUND'))
      }
    }

    const _values = []
    for (const value of values) {
      const _value = new Value({
        language: value.language,
        value: value.value,
      })
      await _value.save()
      _values.push(_value._id)
    }

    const category = new Category({ values: _values, featured })
    await category.save()

    if (image) {
      const _image = path.join(env.CDN_TEMP_CATEGORIES, image)

      if (await helper.exists(_image)) {
        const filename = `${category._id}_${Date.now()}${path.extname(image)}`
        const newPath = path.join(env.CDN_CATEGORIES, filename)

        await fs.rename(_image, newPath)
        category.image = filename
        await category.save()
      }
    }

    return res.status(200).send(category)
  } catch (err) {
    logger.error(`[category.create] ${i18n.t('DB_ERROR')} ${req.body}`, err)
    return res.status(400).send(i18n.t('DB_ERROR') + err)
  }
}
Enter fullscreen mode Exit fullscreen mode

In this function, we retrieve the body of the request, we iterate through the values provided in the body (one value per language) and we create a Value. Finally, we create the category depending on the created values and image file.

Frontend

The frontend is a web application built with Next.js and MUI. From the frontend, the user can search for available products, add them to cart and proceed to checkout depending on delivery and payment methods available.

  • ./frontend/public/ folder contains public assets.
  • ./frontend/src/styles/ folder contains CSS styles.
  • ./frontend/src/components/ folder contains React components.
  • ./frontend/src/lang/ contains locale files.
  • ./frontend/src/app/ folder contains Next.js pages.
  • ./frontend/src/lib/ contains server actions.
  • ./frontend/next.config.ts is the main configuration file of the frontend.

The frontend was created with create-next-app:

npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

In Next.js, a page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. Each page is associated with a route based on its file name.

By default, Next.js pre-renders every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript. Pre-rendering can result in better performance and SEO.

Each generated HTML is associated with minimal JavaScript code necessary for that page. When a page is loaded by the browser, its JavaScript code runs and makes the page fully interactive. (This process is called hydration.)

the frontend uses Server-Side Rendering for SEO optimization so that products can be indexed by search engines.

Admin Dashboard

The admin dashboard is a web application built with Next.js and MUI. From the admin dashboard, admins can manage categories, products, orders and users. When a new order is created, the admin user gets a notification and receives an email.

  • ./backend/public/ folder contains public assets.
  • ./backend/src/styles/ folder contains CSS styles.
  • ./backend/src/components/ folder contains React components.
  • ./backend/src/lang/ contains locale files.
  • ./backend/src/app/ folder contains Next.js pages.
  • ./backend/src/lib/ contains server actions.
  • ./backend/next.config.ts is the main configuration file of the backend.

The admin dashboard was created with create-next-app too:

npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

Resources

  1. Overview
  2. Installing (Self-hosted)
  3. Installing (Docker)
    1. Docker Image
    2. SSL
  4. Setup Stripe
  5. Run from Source
  6. Demo Database
    1. Windows, Linux and macOS
    2. Docker
  7. Change Language and Currency
  8. Add New Language
  9. Unit Tests and Coverage
  10. Logs

That's it! I hope you enjoyed reading.

💖 💪 🙅 🚩
aelassas
aelassas

Posted on November 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related