Efficiently manage your product inventory with Stocklyβa modern, secure, and responsive inventory management web application built with Next.js, React, Prisma, and MongoDB.
- Live-Demo: https://stockly-inventory.vercel.app/
Stockly is designed to help businesses and individuals efficiently manage their product inventory. It provides a robust, full-stack solution with secure authentication, CRUD operations, filtering, sorting, analytics dashboard, QR code generation, data export capabilities, and a beautiful UI powered by shadcn/ui and Tailwind CSS. The project is open source and intended for learning, extension, and real-world use.
- Product Management: Complete CRUD operations for products with SKU tracking
- Category Management: Organize products with custom categories
- Supplier Management: Track and manage product suppliers
- Real-time Search: Instant filtering by product name or SKU
- Advanced Filtering: Filter by category, supplier, and status
- Responsive Design: Works seamlessly on desktop, tablet, and mobile
- Dark/Light Theme: Toggle between themes with system preference detection
- π Analytics Dashboard: Comprehensive business insights with charts and metrics
- π Data Visualization: Interactive charts showing inventory trends and statistics
- π Advanced Search: Enhanced search with multiple filter options
- π± QR Code Generation: Generate QR codes for products with click-to-view functionality
- π Data Export: Export product data to CSV and Excel formats
- π API Documentation: Built-in API documentation page with endpoint details
- π§ API Status Monitor: Real-time API health monitoring and status dashboard
β οΈ Low Stock Alerts: Visual alerts for products with low inventory- π Performance Optimizations: React memoization, lazy loading, and caching
- JWT Authentication: Secure token-based authentication
- User Registration: Secure account creation with password hashing
- Session Management: Persistent login sessions with automatic token refresh
- Protected Routes: Automatic redirection for unauthenticated users
- Password Security: bcryptjs hashing for secure password storage
- Loading States: Visual feedback during all operations
- Toast Notifications: Success/error messages for all user actions
- Form Validation: Client-side validation with error handling
- Accessibility: ARIA-compliant components for screen readers
- Keyboard Navigation: Full keyboard accessibility support
- Consistent Navigation: AppHeader displayed on all authenticated pages
- Next.js 15.0.3: React framework with App Router
- React 19: Latest React with concurrent features
- TypeScript: Type-safe development
- Tailwind CSS: Utility-first CSS framework
- Shadcn/ui: Modern component library
- Zustand: Lightweight state management
- React Hook Form: Form handling with validation
- React Table: Advanced table functionality
- Recharts: Data visualization and charting library
- QRCode: QR code generation library
- Papaparse: CSV parsing and generation
- XLSX: Excel file generation
- Next.js API Routes: Server-side API endpoints
- Prisma ORM: Type-safe database operations
- MongoDB: NoSQL database
- JWT: JSON Web Token authentication
- bcryptjs: Password hashing
- Axios: HTTP client for API requests
- ESLint: Code linting and formatting
- PostCSS: CSS processing
- Autoprefixer: CSS vendor prefixing
- TypeScript: Static type checking
stockly/
βββ app/ # Next.js App Router
β βββ AppHeader/ # Application header component
β β βββ AppHeader.tsx # Main header with theme toggle
β β βββ ModeToggle.tsx # Dark/light theme toggle
β βββ AppTable/ # Main table component
β β βββ AppTable.tsx # Main table wrapper
β β βββ dropdowns/ # Filter dropdowns
β β β βββ CategoryDropDown.tsx
β β β βββ StatusDropDown.tsx
β β β βββ SupplierDropDown.tsx
β β βββ ProductDialog/ # Product management dialogs
β β βββ AddProductDialog.tsx
β β βββ AddCategoryDialog.tsx
β β βββ AddSupplierDialog.tsx
β β βββ _components/ # Dialog sub-components
β βββ Products/ # Product-related components
β β βββ ProductTable.tsx # Main product table
β β βββ columns.tsx # Table column definitions
β β βββ ProductsDropDown.tsx # Product action dropdown
β β βββ PaginationSelection.tsx
β βββ analytics/ # Analytics dashboard
β β βββ page.tsx # Analytics page with charts
β βββ api-docs/ # API documentation
β β βββ page.tsx # API docs page
β βββ api-status/ # API status monitoring
β β βββ page.tsx # API status page
β βββ login/ # Authentication pages
β β βββ page.tsx
β βββ register/
β β βββ page.tsx
β βββ logout/
β β βββ page.tsx
β βββ authContext.tsx # Authentication context
β βββ useProductStore.ts # Zustand store for state management
β βββ types.ts # TypeScript type definitions
β βββ layout.tsx # Root layout
β βββ page.tsx # Main page
β βββ Home.tsx # Home component
βββ components/ # Reusable UI components
β βββ ui/ # Shadcn/ui components
β β βββ button.tsx
β β βββ dialog.tsx
β β βββ input.tsx
β β βββ table.tsx
β β βββ toast.tsx
β β βββ qr-code.tsx # QR code component
β β βββ qr-code-hover.tsx # QR code hover component
β β βββ analytics-card.tsx # Analytics metrics card
β β βββ chart-card.tsx # Chart wrapper component
β β βββ advanced-search.tsx # Advanced search component
β β βββ forecasting-card.tsx # Forecasting insights card
β β βββ progress.tsx # Progress bar component
β βββ GlobalLoading.tsx # Global loading component
β βββ Loading.tsx # Loading spinner
β βββ Skeleton.tsx # Skeleton loading
βββ pages/ # API routes
β βββ api/
β βββ auth/ # Authentication endpoints
β β βββ login.ts
β β βββ register.ts
β β βββ logout.ts
β β βββ session.ts
β βββ products/ # Product management
β β βββ index.ts
β βββ categories/ # Category management
β β βββ index.ts
β βββ suppliers/ # Supplier management
β βββ index.ts
βββ prisma/ # Database schema and client
β βββ schema.prisma # Database schema
β βββ client.ts # Prisma client
β βββ product.ts # Product operations
β βββ category.ts # Category operations
β βββ supplier.ts # Supplier operations
βββ utils/ # Utility functions
β βββ auth.ts # Authentication utilities
β βββ axiosInstance.ts # Axios configuration
βββ hooks/ # Custom React hooks
β βββ use-toast.ts # Toast hook
βββ middleware/ # Next.js middleware
β βββ authMiddleware.ts # Authentication middleware
βββ middleware.ts # Route protection middleware
βββ public/ # Static assets
βββ favicon.ico
βββ ... # Other static files
- Node.js: Version 18 or higher
- npm or yarn: Package manager
- MongoDB: Database (local or cloud instance)
- Git: Version control
-
Clone the repository
git clone https://github.com/your-username/stockly.git cd stockly
-
Install dependencies
npm install # or yarn install
-
Environment Setup
Create a
.env
file in the root directory:# Database Configuration # DATABASE_URL="mongodb://localhost:27017/stockly" # or for MongoDB Atlas: DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/stockly?retryWrites=true&w=majority" # JWT Configuration JWT_SECRET="your-super-secret-jwt-key-here" # JWT_EXPIRES_IN="1h" # Application Configuration (Optional) # NEXTAUTH_URL="http://localhost:3000" # NEXTAUTH_SECRET="your-nextauth-secret"
-
Database Setup
# Generate Prisma client npx prisma generate # Push schema to database npx prisma db push # (Optional) View database in Prisma Studio npx prisma studio
-
Run the development server
npm run dev # or yarn dev
-
Open your browser Navigate to http://localhost:3000
Variable | Description | Example |
---|---|---|
DATABASE_URL |
MongoDB connection string | mongodb://localhost:27017/stockly |
JWT_SECRET |
Secret key for JWT tokens | your-super-secret-jwt-key-here |
JWT_EXPIRES_IN |
JWT token expiration time | 1h |
Variable | Description | Default |
---|---|---|
NEXTAUTH_URL |
NextAuth.js URL | http://localhost:3000 |
NEXTAUTH_SECRET |
NextAuth.js secret | Auto-generated |
- Create a MongoDB Atlas account
- Create a new cluster
- Get your connection string
- Replace
username
,password
, andcluster
with your values - Add the connection string to your
.env
file
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @db.Date
email String @unique
name String
password String
updatedAt DateTime? @db.Date
username String? @unique
}
model Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
categoryId String @db.ObjectId
createdAt DateTime @db.Date
name String
price Float
quantity BigInt
sku String @unique
status String
supplierId String @db.ObjectId
userId String @db.ObjectId
}
model Category {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
userId String @db.ObjectId
}
model Supplier {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
userId String @db.ObjectId
}
Register a new user account.
// Request Body
{
"name": "John Doe",
"email": "john@example.com",
"password": "securepassword123"
}
// Response
{
"success": true,
"message": "User registered successfully"
}
Authenticate user and get JWT token.
// Request Body
{
"email": "john@example.com",
"password": "securepassword123"
}
// Response
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com"
}
}
Logout user and invalidate session.
// Response
{
"success": true,
"message": "Logged out successfully"
}
Get current user session information.
// Response
{
"user": {
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
}
Get all products for the authenticated user.
// Response
[
{
id: "507f1f77bcf86cd799439011",
name: "Laptop",
sku: "LAP001",
price: 999.99,
quantity: 10,
status: "Available",
category: "Electronics",
supplier: "TechCorp",
createdAt: "2024-01-01T00:00:00.000Z",
},
];
Create a new product.
// Request Body
{
"name": "Laptop",
"sku": "LAP001",
"price": 999.99,
"quantity": 10,
"status": "Available",
"categoryId": "507f1f77bcf86cd799439011",
"supplierId": "507f1f77bcf86cd799439012"
}
// Response
{
"id": "507f1f77bcf86cd799439013",
"name": "Laptop",
"sku": "LAP001",
"price": 999.99,
"quantity": 10,
"status": "Available",
"category": "Electronics",
"supplier": "TechCorp",
"createdAt": "2024-01-01T00:00:00.000Z"
}
Update an existing product.
// Request Body
{
"id": "507f1f77bcf86cd799439013",
"name": "Updated Laptop",
"sku": "LAP001",
"price": 1099.99,
"quantity": 15,
"status": "Available",
"categoryId": "507f1f77bcf86cd799439011",
"supplierId": "507f1f77bcf86cd799439012"
}
Delete a product.
// Request Body
{
"id": "507f1f77bcf86cd799439013"
}
// Response
204 No Content
Get all categories for the authenticated user.
Create a new category.
Update an existing category.
Delete a category.
Get all suppliers for the authenticated user.
Create a new supplier.
Update an existing supplier.
Delete a supplier.
The application uses Zustand for state management, providing a simple and efficient way to manage global state.
// Example: Product Store
interface ProductState {
allProducts: Product[];
categories: Category[];
suppliers: Supplier[];
isLoading: boolean;
loadProducts: () => Promise<void>;
addProduct: (product: Product) => Promise<{ success: boolean }>;
updateProduct: (product: Product) => Promise<{ success: boolean }>;
deleteProduct: (id: string) => Promise<{ success: boolean }>;
}
export const useProductStore = create<ProductState>((set) => ({
allProducts: [],
categories: [],
suppliers: [],
isLoading: false,
loadProducts: async () => {
set({ isLoading: true });
try {
const response = await axiosInstance.get("/products");
set({ allProducts: response.data || [] });
} catch (error) {
console.error("Error loading products:", error);
} finally {
set({ isLoading: false });
}
},
// ... other methods
}));
The authentication context provides user state and authentication methods throughout the application.
// Example: Auth Context Usage
const { isLoggedIn, user, login, logout } = useAuth();
// Protected route example
useEffect(() => {
if (!isLoggedIn) {
router.push("/login");
}
}, [isLoggedIn, router]);
All dialogs follow a consistent pattern with proper accessibility attributes:
// Example: Product Dialog
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent aria-describedby="product-dialog-description">
<DialogHeader>
<DialogTitle>Add Product</DialogTitle>
</DialogHeader>
<DialogDescription id="product-dialog-description">
Fill in the product details below.
</DialogDescription>
{/* Form content */}
</DialogContent>
</Dialog>
The product table uses React Table for advanced functionality:
// Example: Table Column Definition
const columns: ColumnDef<Product>[] = [
{
accessorKey: "name",
header: "Product Name",
cell: ({ row }) => <div>{row.getValue("name")}</div>,
},
{
accessorKey: "sku",
header: "SKU",
},
// ... other columns
];
QR code generation with click-to-view functionality:
// Example: QR Code Usage
<QRCodeHover
value={`Product: ${product.name}\nSKU: ${product.sku}\nPrice: $${product.price}`}
title="View QR Code"
/>
Reusable analytics cards and charts:
// Example: Analytics Card
<AnalyticsCard
title="Total Products"
value={totalProducts}
description="Total products in inventory"
icon={<Package className="h-4 w-4" />}
/>
- Secure token-based authentication
- Automatic token refresh
- Protected API routes
- Session management
- bcryptjs hashing for passwords
- Secure password validation
- No plain text password storage
- Request validation
- Error handling without sensitive data exposure
- CORS protection
- Rate limiting (can be implemented)
- Client-side form validation
- Server-side data validation
- TypeScript type safety
- Prisma schema validation
The search functionality filters products instantly as users type:
// Search implementation in ProductTable.tsx
const filteredData = useMemo(() => {
return data.filter((product) => {
const searchMatch = searchTerm
? product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
product.sku.toLowerCase().includes(searchTerm.toLowerCase())
: true;
return searchMatch && categoryFilter && supplierFilter && statusFilter;
});
}, [data, searchTerm, categoryFilter, supplierFilter, statusFilter]);
Consistent user feedback with toast notifications:
// Example: Success toast
toast({
title: "Success!",
description: "Product created successfully.",
variant: "default",
});
// Example: Error toast
toast({
title: "Error",
description: "Failed to create product. Please try again.",
variant: "destructive",
});
Visual feedback during async operations:
// Example: Button loading state
<Button disabled={isLoading}>
{isLoading ? "Creating..." : "Create Product"}
</Button>
Dark/light theme with system preference detection:
// Theme toggle implementation
const { theme, setTheme } = useTheme();
const toggleTheme = () => {
setTheme(theme === "dark" ? "light" : "dark");
};
CSV and Excel export functionality:
// Example: Export to CSV
const exportToCSV = () => {
const csv = Papa.unparse(filteredProducts);
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", "products.csv");
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
Comprehensive business insights with charts:
// Example: Analytics implementation
const analyticsData = useMemo(() => {
return {
totalProducts: products.length,
totalValue: products.reduce(
(sum, p) => sum + p.price * Number(p.quantity),
0
),
lowStockItems: products.filter((p) => Number(p.quantity) < 10).length,
categories: categoryStats,
monthlyTrends: monthlyData,
};
}, [products]);
- Connect your GitHub repository to Vercel
- Set environment variables in Vercel dashboard
- Deploy automatically on push to main branch
DATABASE_URL="your-production-mongodb-url"
JWT_SECRET="your-production-jwt-secret"
# Build the application
npm run build
# Start production server
npm start
# Run linting
npm run lint
- User registration and login
- Product CRUD operations
- Category management
- Supplier management
- Search and filtering
- Theme toggle
- Responsive design
- Form validation
- Error handling
- Loading states
- Analytics dashboard
- QR code generation
- Data export (CSV/Excel)
- API documentation page
- API status monitoring
# Install testing dependencies
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
# Run tests
npm test
# Run tests with coverage
npm test -- --coverage
- Create new API endpoints in
pages/api/
- Add new Prisma models in
schema.prisma
- Create new components in
components/
- Update state management in
useProductStore.ts
- Add new routes in
app/
The application uses Tailwind CSS with custom design tokens:
// tailwind.config.ts
export default {
theme: {
extend: {
colors: {
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
// ... other custom colors
},
},
},
};
All UI components are built with Shadcn/ui and can be customized:
# Add new Shadcn/ui components
npx shadcn@latest add [component-name]
# Check database connection
npx prisma db pull
# Reset database (development only)
npx prisma db push --force-reset
# Clear Next.js cache
rm -rf .next
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install
- Check JWT_SECRET environment variable
- Verify database connection
- Check user credentials in database
- Enable Next.js production mode
- Optimize images and assets
- Use proper caching strategies
- Ensure QR code library is properly installed
- Check for hydration mismatches in development
- Verify client-side rendering for dynamic content
-
Fork the repository
-
Create a feature branch
git checkout -b feature/your-feature-name
-
Make your changes
-
Test thoroughly
-
Commit your changes
git commit -m "feat: add new feature"
-
Push to your fork
git push origin feature/your-feature-name
-
Create a pull request
- Use TypeScript for type safety
- Follow ESLint rules
- Write meaningful commit messages
- Add comments for complex logic
- Test your changes
This project is licensed under the MIT License - see the LICENSE file for details.
- Next.js Team for the amazing framework
- Vercel for hosting and deployment
- Prisma Team for the excellent ORM
- Shadcn/ui for the beautiful components
- Tailwind CSS for the utility-first CSS framework
- Recharts for the data visualization library
If you encounter any issues or have questions:
- Check the troubleshooting section
- Search existing issues
- Create a new issue with detailed information
- Contact the maintainer
- User roles and permissions
- Advanced reporting and analytics
- Bulk import/export functionality
- Email notifications
- Mobile app
- API rate limiting
- Advanced search filters
- Product images
- Inventory alerts
- Audit logs
- Real-time notifications
- Advanced forecasting algorithms
- Multi-language support
- Advanced user preferences
- Database indexing optimization
- Caching strategies
- Code splitting
- Image optimization
- Bundle size optimization
- Server-side rendering improvements
- Progressive Web App (PWA) features
- Lines of Code: ~8,000+
- Components: 30+
- API Endpoints: 12+
- Database Models: 4
- Dependencies: 40+
- Pages: 8+
- Features: 20+
Feature | Status | Description |
---|---|---|
User Authentication | β Complete | JWT-based auth with registration/login |
Product Management | β Complete | Full CRUD with search and filtering |
Category Management | β Complete | Create, edit, delete categories |
Supplier Management | β Complete | Manage product suppliers |
Responsive Design | β Complete | Mobile-first design |
Dark/Light Theme | β Complete | Theme toggle with system preference |
Real-time Search | β Complete | Instant product filtering |
Toast Notifications | β Complete | User feedback system |
Loading States | β Complete | Visual feedback during operations |
Form Validation | β Complete | Client and server-side validation |
Accessibility | β Complete | ARIA-compliant components |
TypeScript | β Complete | Full type safety |
Database Integration | β Complete | MongoDB with Prisma ORM |
API Security | β Complete | Protected routes and validation |
Analytics Dashboard | β Complete | Business insights with charts |
QR Code Generation | β Complete | Product QR codes with click-to-view |
Data Export | β Complete | CSV and Excel export functionality |
API Documentation | β Complete | Built-in API docs page |
API Status Monitor | β Complete | Real-time API health monitoring |
Performance Optimizations | β Complete | React memoization and caching |
Low Stock Alerts | β Complete | Visual alerts for low inventory |
Advanced Search | β Complete | Enhanced search with multiple filters |
Feel free to use this project repository and extend this project further!
If you have any questions or want to share your work, reach out via GitHub or my portfolio at https://arnob-mahmud.vercel.app/.
Enjoy building and learning! π
Thank you! π