Skip to content
jonbontoPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

37 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

E-Commerce Frontend (Next.js + React + TypeScript)

A complete, responsive e-commerce frontend with JWT authentication, admin panel, and shopping cart. Built with Next.js 16, React 19, TypeScript, and Tailwind CSS.

🎯 Features

  • 🔐 Full Authentication - Sign up, login, logout with JWT tokens
  • 👨‍💼 Admin Panel - Create, edit, delete products (admin-only)
  • 📱 Fully Responsive - Mobile-first design
  • 🛍️ Product Catalog - Browse all active products
  • 🛒 Shopping Cart - Add/remove items with Zustand state management
  • 💳 Checkout - Order summary and checkout form
  • 🔄 Real-time Sync - Cart syncs with backend
  • ⚡ Next.js 16 - App Router with modern features
  • 🎨 Tailwind CSS - Utility-first styling
  • 📦 TypeScript - Full type safety
  • 🎯 SEO Friendly - Optimized metadata

📋 Prerequisites

  • Node.js 18+
  • NestJS backend running at http://localhost:3000/api

🚀 Quick Start

1. Install dependencies

npm install

2. Configure environment variables

Create .env.local:

NEXT_PUBLIC_API_URL=http://localhost:3000/api

3. Start development server

npm run dev

Open http://localhost:3001 in your browser.

📂 Project Structure

src/
├── app/                              # Next.js App Router
│   ├── layout.tsx                   # Root layout
│   ├── page.tsx                     # Product catalog
│   ├── (auth)/
│   │   ├── login/page.tsx           # Login page
│   │   └── register/page.tsx        # Registration page
│   ├── products/[id]/page.tsx       # Product details
│   ├── cart/page.tsx                # Shopping cart
│   ├── checkout/page.tsx            # Checkout
│   └── admin/                       # Admin routes (protected)
│       ├── page.tsx                 # Product management
│       ├── products/new/page.tsx    # Create product
│       └── products/[id]/edit/page.tsx # Edit product
├── components/
│   ├── Navbar.tsx                   # Navigation with auth
│   ├── Footer.tsx                   # Footer
│   ├── AuthProvider.tsx             # Auth initialization
│   ├── AdminGuard.tsx               # Route protection
│   ├── ProductCard.tsx              # Product card
│   ├── CartItem.tsx                 # Cart item
│   ├── Button.tsx                   # Button component
│   ├── QuantityInput.tsx            # Quantity selector
│   ├── Loader.tsx                   # Loading spinner
│   └── EmptyState.tsx               # Empty state
├── lib/
│   ├── api.ts                       # Axios instance
│   └── fetcher.ts                   # API functions
├── store/
│   ├── auth.ts                      # Auth store (Zustand)
│   └── cart.store.ts                # Cart store (Zustand)
├── types/
│   └── index.ts                     # TypeScript types
└── globals.css                      # Global styles

🔐 Authentication Flow

Sign Up

POST /api/auth/signup
Body: { name, email, password }
Response: { user, token }

New users are created with role user.

Login

POST /api/auth/login
Body: { email, password }
Response: { user, token }

Credentials are stored in localStorage and sent with every API request.

Demo Admin Account

Email: admin@example.com
Password: admin123

Protected Routes

  • /admin - Admin-only (redirects non-admin users to home)
  • /admin/products/new - Create product (admin-only)
  • /admin/products/:id/edit - Edit product (admin-only)

📡 API Integration

All API calls use JWT authentication. Tokens are:

  • Stored in localStorage in auth-store
  • Sent as Authorization: Bearer <token> header
  • Also set as jwt cookie

Auth Endpoints

  • POST /api/auth/signup - Register
  • POST /api/auth/login - Login
  • GET /api/auth/me - Current user
  • POST /api/auth/logout - Logout

Product Endpoints

  • GET /api/products - List all products
  • GET /api/products/:id - Get product details
  • GET /api/admin/products - Admin: List all (including inactive)
  • POST /api/admin/products - Admin: Create product
  • PUT /api/admin/products/:id - Admin: Update product
  • DELETE /api/admin/products/:id - Admin: Delete product

Cart Endpoints

  • GET /api/cart - Get cart
  • POST /api/cart/items - Add item
  • PUT /api/cart/items/:id - Update quantity
  • DELETE /api/cart/items/:id - Remove item

🎛️ State Management

Auth Store (Zustand)

import { useAuthStore } from '@/store/auth';

const user = useAuthStore((state) => state.user);
const token = useAuthStore((state) => state.token);
const setAuth = useAuthStore((state) => state.setAuth);
const logout = useAuthStore((state) => state.logout);

Features:

  • Persistent storage with localStorage
  • Automatic deserialization on app load
  • Type-safe user and token

Cart Store (Zustand)

import { useCartStore } from '@/store/cart.store';

const cart = useCartStore((state) => state.cart);
const addToCart = useCartStore((state) => state.addToCart);

Features:

  • Session-based cart management
  • Optimistic updates
  • Backend synchronization

📄 Routes & Pages

Route Component Protected Notes
/ Product Catalog No Browse products
/login Login Form No User login
/register Registration Form No New user signup
/products/:id Product Details No View product details
/cart Shopping Cart No Manage cart items
/checkout Checkout No Order review
/admin Product Manager Yes (Admin) CRUD products
/admin/products/new Create Product Yes (Admin) Add new product
/admin/products/:id/edit Edit Product Yes (Admin) Update product

🛠️ Available Scripts

# Development
npm run dev

# Production build
npm run build

# Start production server
npm start

# Run linter
npm run lint

📦 Dependencies

  • next v16 - React framework
  • react v19 - UI library
  • typescript v5 - Type safety
  • tailwindcss v4 - Utility CSS
  • axios - HTTP client
  • zustand v5 - State management

🎨 Styling

  • Framework: Tailwind CSS v4
  • Approach: Utility-first CSS
  • Responsive: Mobile-first breakpoints
  • Colors: Blue primary theme with gray accents

Example Classes

// Buttons
<button className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
  Click me
</button>

// Cards
<div className="bg-white rounded-lg shadow p-6">
  Content
</div>

// Responsive grid
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  {/* Items */}
</div>

🔒 Security

  • Passwords hashed with bcrypt on backend
  • JWT tokens expire after 7 days
  • HttpOnly cookies for additional security
  • CORS enabled with credentials
  • Input validation on both client and server

⚠️ Error Handling

All API calls include error handling:

try {
  const response = await authApi.login(credentials);
  // Handle success
} catch (err) {
  const message = err instanceof Error ? err.message : 'Unknown error';
  setError(message);
}

🐛 Troubleshooting

Backend not connecting

  1. Ensure backend runs on http://localhost:3000
  2. Check NEXT_PUBLIC_API_URL in .env.local
  3. Verify CORS is enabled on backend
  4. Check browser DevTools Network tab for failed requests

Auth not persisting

  1. Check localStorage is enabled
  2. Verify auth-store key in localStorage
  3. Clear localStorage and login again

Admin routes not accessible

  1. Login with admin credentials
  2. Check user role: admin@example.com
  3. Verify JWT token is sent in requests

Images not loading

  1. Check image URL validity
  2. Verify backend serves /uploads/products/*
  3. Check CORS headers allow image requests

🚀 Performance

  • Image optimization with Next.js
  • Code splitting with App Router
  • Lazy loading for routes
  • Optimistic cart updates
  • Zustand for minimal re-renders

📚 Environment Variables

Variable Description Example
NEXT_PUBLIC_API_URL Backend API URL http://localhost:3000/api

🔮 Future Enhancements

  • Product search and filtering
  • User wishlist
  • Order history
  • Product reviews
  • Payment integration (Stripe)
  • Email notifications
  • Analytics dashboard
  • Inventory management

📝 Notes

  • Admin panel only visible to users with role: "admin"
  • Cart is session-based on the backend
  • Products must have isActive: true to appear in catalog
  • Images can be uploaded during product creation/edit

License

Proprietary - Internal use only.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages