Modern homepage with hero section, featured products, and category navigation
Advanced product catalog with filtering, search, sorting, and pagination capabilities
Detailed product page with image gallery, customer reviews, ratings, and purchase options
Interactive shopping cart with quantity controls, price calculations, and secure checkout
Beautiful dark mode interface with automatic theme switching and modern aesthetics
Fully responsive design optimized for mobile devices with touch-friendly interface
User profile page with account settings, order history, and personal information
Secure authentication interface with login and registration forms
Comprehensive admin dashboard for managing products, orders, and customers
Keyboard shortcuts guide for enhanced accessibility and productivity
Featured products section highlighting popular and trending items
๐ฏ SvelteKit 2.0+ # Full-stack framework with SSR/SSG
๐ฏ TypeScript 5.0+ # Type-safe development
๐ฏ Vite 5.0+ # Lightning-fast build tool
๐จ Tailwind CSS 3.3+ # Utility-first CSS framework
๐จ Svelte 4.2+ # Reactive UI framework
๐จ PostCSS 8.4+ # CSS processing
๐ง Node.js 20+ # Runtime environment
๐ง Stripe SDK # Payment processing
๐ง Zod 3.22+ # Schema validation
๐งช Vitest 1.0+ # Unit testing framework
๐งช Playwright # E2E testing
๐งช ESLint 8.0+ # Code linting
๐งช Prettier 2.8+ # Code formatting
๐ Vercel # Recommended hosting platform
๐ Netlify # Alternative hosting
๐ Node.js Adapter # Self-hosted option
Before you begin, ensure you have the following installed:
git clone https://github.com/michaelgermini/Modern-SvelteKit-Webshop.git
cd modern-sveltekit-webshop
npm install
cp env.example .env
# Edit .env with your Stripe keys and configuration
npm run dev
http://localhost:5173
Create a .env
file in the root directory:
# Stripe Configuration
STRIPE_SECRET_KEY=sk_test_your_secret_key_here
PUBLIC_STRIPE_PK=pk_test_your_publishable_key_here
# Application Configuration
BASE_URL=http://localhost:5173
NODE_ENV=development
# Optional: Analytics, Email, etc.
GOOGLE_ANALYTICS_ID=your_ga_id
RESEND_API_KEY=your_resend_key
modern-sveltekit-webshop/
โโโ ๐ src/
โ โโโ ๐ lib/
โ โ โโโ ๐ components/ # 25+ Reusable UI Components
โ โ โ โโโ ๐ ProductCard.svelte
โ โ โ โโโ ๐๏ธ ShoppingCart.svelte
โ โ โ โโโ ๐จ ThemeToggle.svelte
โ โ โ โโโ ๐ SearchBar.svelte
โ โ โโโ ๐ stores/ # Svelte State Management
โ โ โ โโโ ๐ cart.ts # Shopping cart logic
โ โ โ โโโ ๐ theme.ts # Dark/light mode
โ โ โ โโโ ๐ auth.ts # User authentication
โ โ โ โโโ ๐ favorites.ts # Wishlist management
โ โ โโโ ๐ services/ # Business Logic Layer
โ โ โ โโโ ๐๏ธ products.ts # Product management
โ โ โ โโโ ๐ณ stripe.ts # Payment processing
โ โ โ โโโ ๐ง email.ts # Email notifications
โ โ โโโ ๐ utils/ # Utility Functions
โ โ โ โโโ ๐ฐ formatPrice.ts # Currency formatting
โ โ โ โโโ ๐ search.ts # Search algorithms
โ โ โ โโโ ๐ analytics.ts # Usage tracking
โ โ โโโ ๐ types/ # TypeScript Definitions
โ โ โ โโโ ๐๏ธ product.ts # Product interfaces
โ โ โ โโโ ๐ cart.ts # Cart types
โ โ โ โโโ ๐ค user.ts # User management
โ โ โโโ ๐ hooks/ # Custom Svelte Hooks
โ โ โโโ ๐ฃ useInfiniteScroll.ts
โ โโโ ๐ routes/ # SvelteKit Routes
โ โ โโโ ๐ +page.svelte # Homepage
โ โ โโโ ๐๏ธ products/+page.svelte # Product catalog
โ โ โโโ ๐ฆ product/[slug]/+page.svelte # Product details
โ โ โโโ ๐ cart/+page.svelte # Shopping cart
โ โ โโโ ๐ค profile/+page.svelte # User profile
โ โ โโโ ๐ admin/ # Admin dashboard
โ โ โโโ ๐ง api/ # Server endpoints
โ โ โโโ ๐ณ checkout/+server.ts
โ โ โโโ ๐ช webhook/+server.ts
โ โโโ ๐ app.html # HTML template
โ โโโ ๐จ app.css # Global styles
โ โโโ ๐ง app.d.ts # TypeScript declarations
โโโ ๐ static/ # Static Assets
โ โโโ ๐ผ๏ธ img/products/ # Product images (25+ SVG)
โ โโโ ๐ฏ favicon.ico # Site favicon
โ โโโ ๐ฑ manifest.json # PWA manifest
โ โโโ ๐ค robots.txt # SEO robots
โ โโโ ๐ง sw.js # Service worker
โโโ โ๏ธ Configuration Files
โ โโโ ๐ฆ package.json # Dependencies & scripts
โ โโโ ๐ ๏ธ svelte.config.js # SvelteKit config
โ โโโ โก vite.config.ts # Build tool config
โ โโโ ๐จ tailwind.config.js # Styling config
โ โโโ ๐ tsconfig.json # TypeScript config
โ โโโ ๐งช vitest.config.ts # Testing config
โโโ ๐ Documentation
โ โโโ ๐ README.md # This file
โ โโโ ๐ค CONTRIBUTING.md # Contribution guidelines
โ โโโ ๐ SECURITY.md # Security policy
โ โโโ ๐ USAGE_GUIDE.md # Usage instructions
โ โโโ ๐ LICENSE # MIT license
โโโ ๐ง Development Tools
โโโ ๐ .github/workflows/ # GitHub Actions CI/CD
โโโ ๐ฏ .gitignore # Git ignore rules
โโโ ๐ง .eslintrc.cjs # ESLint config
โโโ ๐จ .prettierrc # Prettier config
User Interaction โ Component โ Store โ Service โ API โ Database
โ
UI Updates โ Store โ Component
Our curated collection includes 52 premium products across multiple categories:
Our Stripe integration provides enterprise-grade payment processing:
// Server-side checkout session creation
export async function POST({ request }) {
const { items, successUrl, cancelUrl } = await request.json();
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: items.map(item => ({
price_data: {
currency: 'eur',
product_data: { name: item.name },
unit_amount: item.price,
},
quantity: item.quantity,
})),
mode: 'payment',
success_url: successUrl,
cancel_url: cancelUrl,
});
return json({ sessionId: session.id });
}
Secure webhook processing for payment confirmations:
export async function POST({ request }) {
const signature = request.headers.get('stripe-signature');
const body = await request.text();
try {
const event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
switch (event.type) {
case 'checkout.session.completed':
// Handle successful payment
await handlePaymentSuccess(event.data.object);
break;
case 'payment_intent.payment_failed':
// Handle payment failure
await handlePaymentFailure(event.data.object);
break;
}
return json({ received: true });
} catch (err) {
throw error(400, 'Webhook signature verification failed');
}
}
Automatic theme switching with system preference detection:
// Theme store with automatic detection
function getSystemTheme(): 'light' | 'dark' {
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
}
// Apply theme to document
function setThemeClass(theme: 'light' | 'dark') {
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(theme);
}
Mobile-first approach with comprehensive breakpoints:
/* Responsive grid system */
.grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); }
@media (min-width: 640px) {
.sm\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (min-width: 768px) {
.md\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@media (min-width: 1024px) {
.lg\:grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
WCAG 2.1 AA compliant implementation:
Service worker implementation for offline functionality:
// Service worker registration
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('SW registered:', registration.scope);
})
.catch(error => {
console.log('SW registration failed:', error);
});
}
# Development
npm run dev # Start development server with HMR
npm run build # Create production build
npm run preview # Preview production build locally
# Quality & Testing
npm run check # TypeScript type checking
npm run lint # ESLint code linting
npm run format # Prettier code formatting
npm run test # Run unit tests with Vitest
npm run test:ui # Run tests with UI interface
# Advanced Testing
npm run test:coverage # Generate test coverage report
npm run test:e2e # Run end-to-end tests
npm run test:performance # Performance testing suite
git clone https://github.com/michaelgermini/Modern-SvelteKit-Webshop.git
cd modern-sveltekit-webshop
npm install
cp env.example .env
# Edit .env with your Stripe keys and configuration
npm run dev
npm run lint
npm run check
npm run test
Our comprehensive testing suite ensures code quality and reliability:
// Example: Product service testing
import { describe, it, expect } from 'vitest';
import { formatPrice } from '$lib/utils/formatPrice';
describe('formatPrice', () => {
it('should format EUR currency correctly', () => {
expect(formatPrice(2500, 'EUR')).toBe('โฌ25.00');
});
it('should handle zero values', () => {
expect(formatPrice(0, 'USD')).toBe('$0.00');
});
});
// Example: Component testing with Testing Library
import { render, screen, fireEvent } from '@testing-library/svelte';
import ProductCard from '$lib/components/ProductCard.svelte';
describe('ProductCard', () => {
it('should display product information', () => {
const product = { name: 'Test Product', price: 1000 };
render(ProductCard, { props: { product } });
expect(screen.getByText('Test Product')).toBeInTheDocument();
expect(screen.getByText('โฌ10.00')).toBeInTheDocument();
});
});
// Example: Playwright E2E test
import { test, expect } from '@playwright/test';
test('complete checkout flow', async ({ page }) => {
await page.goto('/');
await page.click('[data-testid="add-to-cart"]');
await page.click('[data-testid="checkout-button"]');
// Verify Stripe checkout loads
await expect(page).toHaveURL(/checkout.stripe.com/);
});
# Run all tests
npm run test
# Run with coverage
npm run test:coverage
# Run E2E tests
npm run test:e2e
# Run performance tests
npm run test:performance
# Watch mode for development
npm run test:watch
npm install -g vercel
vercel login
vercel link
vercel env add STRIPE_SECRET_KEY
vercel env add PUBLIC_STRIPE_PK
vercel --prod
npm run build
build
STRIPE_SECRET_KEY
and PUBLIC_STRIPE_PK
# Build for production
npm run build
# Start production server
npm run preview
# Or use PM2 for process management
npm install -g pm2
pm2 start "npm run preview" --name "webshop"
# Required
STRIPE_SECRET_KEY=sk_live_your_live_secret_key
PUBLIC_STRIPE_PK=pk_live_your_live_publishable_key
# Optional
NODE_ENV=production
BASE_URL=https://yourdomain.com
GOOGLE_ANALYTICS_ID=GA_MEASUREMENT_ID
Our application implements enterprise-grade security measures:
# Never commit these files
.env
.env.local
.env.production
// Zod schema validation
import { z } from 'zod';
const checkoutSchema = z.object({
items: z.array(z.object({
productId: z.string(),
quantity: z.number().min(1).max(99),
price: z.number().positive()
})),
customerEmail: z.string().email()
});
export async function POST({ request }) {
const body = await request.json();
const validatedData = checkoutSchema.parse(body);
// Proceed with validated data
}
// SvelteKit CSP configuration
export async function handle({ event, resolve }) {
const response = await resolve(event);
response.headers.set(
'Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https:; " +
"connect-src 'self' https://api.stripe.com"
);
return response;
}
// Lazy loading with intersection observer
import { onMount } from 'svelte';
let imgElement: HTMLImageElement;
let isIntersecting = false;
onMount(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
isIntersecting = true;
observer.disconnect();
}
});
}
);
if (imgElement) observer.observe(imgElement);
});
// Dynamic imports for route-based splitting
import { onMount } from 'svelte';
let Component: any;
onMount(async () => {
const module = await import('./HeavyComponent.svelte');
Component = module.default;
});
# Analyze bundle size
npm run build
npx vite-bundle-analyzer dist/
// Core Web Vitals tracking
import { onMount } from 'svelte';
onMount(() => {
// CLS (Cumulative Layout Shift)
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('CLS:', entry.value);
}
}).observe({ entryTypes: ['layout-shift'] });
// FID (First Input Delay)
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('FID:', entry.processingStart - entry.startTime);
}
}).observe({ entryTypes: ['first-input'] });
});
git clone https://github.com/yourusername/Modern-SvelteKit-Webshop.git
cd modern-sveltekit-webshop
git checkout -b feature/amazing-feature
npm run lint
npm run check
npm run test
git commit -m "feat: add amazing feature
- Detailed description of changes
- Reference to issues if applicable
- Breaking changes noted"
git push origin feature/amazing-feature
any
type except when necessary<script lang="ts">
// Imports first
import { createEventDispatcher } from 'svelte';
// Types and interfaces
type Product = {
id: string;
name: string;
price: number;
};
// Props with proper typing
export let product: Product;
export let disabled = false;
// Reactive statements
$: isAvailable = product.stock > 0;
// Event dispatchers
const dispatch = createEventDispatcher<{
addToCart: { product: Product; quantity: number }
}>();
function handleAddToCart() {
dispatch('addToCart', { product, quantity: 1 });
}
</script>
<!-- Template with semantic HTML -->
<button
{disabled}
on:click={handleAddToCart}
class="btn-primary"
aria-label="Add {product.name} to cart"
>
Add to Cart
</button>
type(scope): description
[optional body]
[optional footer]
Types:
feat
: new featurefix
: bug fixdocs
: documentationstyle
: formattingrefactor
: code restructuringtest
: adding testschore
: maintenanceMIT License
Copyright (c) 2024 Modern SvelteKit Webshop
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Please report security vulnerabilities by emailing security@germini.info instead of using public issues.