The web development landscape has evolved dramatically. Today's successful websites aren't just visually appealing—they're lightning-fast, SEO-optimized, secure, and built on modern architectures that support business growth and scalability.
The Modern Website Stack
Gone are the days when a simple HTML/CSS/jQuery combo was sufficient. Modern websites demand sophisticated technology stacks that balance performance, developer experience, and business requirements.
Frontend Frameworks: The Big Three
React Ecosystem
// Modern React with Server Components
// app/page.tsx (Next.js 14+)
import { Suspense } from 'react';
import { ProductList } from '@/components/ProductList';
import { ProductSkeleton } from '@/components/ProductSkeleton';
// Server Component - runs on server
async function getProducts() {
const res = await fetch('https://api.example.com/products', {
cache: 'no-store', // Always fresh data
// Or use: next: { revalidate: 3600 } for ISR
});
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
}
export default async function ProductsPage() {
const products = await getProducts();
return (
<div className="container mx-auto px-4">
<h1 className="text-4xl font-bold mb-8">Our Products</h1>
<Suspense fallback={<ProductSkeleton />}>
<ProductList products={products} />
</Suspense>
</div>
);
}
Vue.js with Composition API
<!-- ProductList.vue -->
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useProductStore } from '@/stores/products';
import { useIntersectionObserver } from '@vueuse/core';
const productStore = useProductStore();
const loading = ref(true);
const page = ref(1);
const target = ref(null);
// Computed property for filtered products
const filteredProducts = computed(() => {
return productStore.products.filter(p => p.inStock);
});
// Infinite scroll implementation
useIntersectionObserver(
target,
([{ isIntersecting }]) => {
if (isIntersecting && !loading.value) {
loadMore();
}
}
);
async function loadMore() {
loading.value = true;
await productStore.fetchProducts(page.value++);
loading.value = false;
}
onMounted(() => {
loadMore();
});
</script>
<template>
<div class="product-grid">
<ProductCard
v-for="product in filteredProducts"
:key="product.id"
:product="product"
@add-to-cart="handleAddToCart"
/>
<div ref="target" class="intersection-trigger" />
<LoadingSpinner v-if="loading" />
</div>
</template>
Angular with Standalone Components
// product-list.component.ts
import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductService } from '@/services/product.service';
import { Product } from '@/models/product.model';
@Component({
selector: 'app-product-list',
standalone: true,
imports: [CommonModule, ProductCardComponent],
template: `
<div class="product-container">
<h2>Products</h2>
@for (product of products(); track product.id) {
<app-product-card [product]="product" />
} @empty {
<p>No products available</p>
}
@if (loading()) {
<app-loading-spinner />
}
</div>
`,
styles: [`
.product-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 2rem;
padding: 2rem;
}
`]
})
export class ProductListComponent implements OnInit {
products = signal<Product[]>([]);
loading = signal(false);
constructor(private productService: ProductService) {}
ngOnInit() {
this.loadProducts();
}
async loadProducts() {
this.loading.set(true);
try {
const data = await this.productService.getProducts();
this.products.set(data);
} catch (error) {
console.error('Failed to load products:', error);
} finally {
this.loading.set(false);
}
}
}
Performance Optimization Strategies
1. Code Splitting and Lazy Loading
// Next.js dynamic imports
import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(() => import('@/components/HeavyComponent'), {
loading: () => <LoadingSkeleton />,
ssr: false // Client-side only if needed
});
const VideoPlayer = dynamic(() => import('@/components/VideoPlayer'), {
loading: () => <div>Loading player...</div>
});
export default function MediaPage() {
return (
<div>
<h1>Media Content</h1>
<Suspense fallback={<div>Loading...</div>}>
<HeavyComponent />
<VideoPlayer src="/videos/demo.mp4" />
</Suspense>
</div>
);
}
2. Image Optimization
// Next.js Image component with optimization
import Image from 'next/image';
export function ProductImage({ product }) {
return (
<div className="relative aspect-square">
<Image
src={product.imageUrl}
alt={product.name}
fill
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
className="object-cover rounded-lg"
priority={product.featured} // Load immediately if featured
placeholder="blur"
blurDataURL={product.thumbnailUrl}
/>
</div>
);
}
// Responsive images with srcset
export function ResponsiveImage({ src, alt }) {
return (
<picture>
<source
media="(max-width: 640px)"
srcSet={`${src}?w=640 640w, ${src}?w=1280 1280w`}
sizes="100vw"
/>
<source
media="(max-width: 1024px)"
srcSet={`${src}?w=1024 1024w, ${src}?w=2048 2048w`}
sizes="100vw"
/>
<img
src={`${src}?w=1920`}
alt={alt}
loading="lazy"
decoding="async"
className="w-full h-auto"
/>
</picture>
);
}
3. API Route Optimization
// Next.js API Route with caching
import { NextRequest, NextResponse } from 'next/server';
import { Redis } from '@upstash/redis';
const redis = Redis.fromEnv();
const CACHE_TTL = 3600; // 1 hour
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const productId = searchParams.get('id');
if (!productId) {
return NextResponse.json(
{ error: 'Product ID required' },
{ status: 400 }
);
}
try {
// Try cache first
const cacheKey = `product:${productId}`;
const cached = await redis.get(cacheKey);
if (cached) {
return NextResponse.json(cached, {
headers: {
'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',
'X-Cache': 'HIT'
}
});
}
// Fetch from database
const product = await db.product.findUnique({
where: { id: productId },
include: {
images: true,
reviews: {
take: 5,
orderBy: { createdAt: 'desc' }
}
}
});
if (!product) {
return NextResponse.json(
{ error: 'Product not found' },
{ status: 404 }
);
}
// Cache the result
await redis.setex(cacheKey, CACHE_TTL, JSON.stringify(product));
return NextResponse.json(product, {
headers: {
'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',
'X-Cache': 'MISS'
}
});
} catch (error) {
console.error('API Error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
SEO Optimization for Modern Websites
Dynamic Metadata Generation
// app/products/[slug]/page.tsx
import { Metadata } from 'next';
interface ProductPageProps {
params: { slug: string };
}
export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
const product = await getProduct(params.slug);
if (!product) {
return {
title: 'Product Not Found',
};
}
return {
title: `${product.name} | Your Store`,
description: product.description,
keywords: product.tags.join(', '),
openGraph: {
title: product.name,
description: product.description,
images: [
{
url: product.imageUrl,
width: 1200,
height: 630,
alt: product.name,
}
],
type: 'product',
siteName: 'Your Store',
},
twitter: {
card: 'summary_large_image',
title: product.name,
description: product.description,
images: [product.imageUrl],
},
alternates: {
canonical: `https://yourstore.com/products/${params.slug}`,
},
robots: {
index: product.isPublished,
follow: product.isPublished,
}
};
}
export default async function ProductPage({ params }: ProductPageProps) {
const product = await getProduct(params.slug);
// JSON-LD structured data
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
description: product.description,
image: product.imageUrl,
offers: {
'@type': 'Offer',
price: product.price,
priceCurrency: 'USD',
availability: product.inStock ? 'InStock' : 'OutOfStock',
url: `https://yourstore.com/products/${params.slug}`,
},
aggregateRating: product.rating && {
'@type': 'AggregateRating',
ratingValue: product.rating.average,
reviewCount: product.rating.count,
}
};
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<ProductDetails product={product} />
</>
);
}
Sitemap Generation
// app/sitemap.ts
import { MetadataRoute } from 'next';
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const baseUrl = 'https://yourwebsite.com';
// Static pages
const staticPages = [
'',
'/about',
'/contact',
'/products',
'/blog',
].map(route => ({
url: `${baseUrl}${route}`,
lastModified: new Date().toISOString(),
changeFrequency: 'daily' as const,
priority: route === '' ? 1 : 0.8,
}));
// Dynamic product pages
const products = await db.product.findMany({
where: { published: true },
select: { slug: true, updatedAt: true }
});
const productPages = products.map(product => ({
url: `${baseUrl}/products/${product.slug}`,
lastModified: product.updatedAt.toISOString(),
changeFrequency: 'weekly' as const,
priority: 0.6,
}));
// Dynamic blog pages
const posts = await db.post.findMany({
where: { published: true },
select: { slug: true, updatedAt: true }
});
const blogPages = posts.map(post => ({
url: `${baseUrl}/blog/${post.slug}`,
lastModified: post.updatedAt.toISOString(),
changeFrequency: 'monthly' as const,
priority: 0.7,
}));
return [...staticPages, ...productPages, ...blogPages];
}
Advanced State Management
Zustand for Lightweight State
// stores/cart.store.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
image: string;
}
interface CartStore {
items: CartItem[];
total: number;
addItem: (item: Omit<CartItem, 'quantity'>) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
clearCart: () => void;
getItemCount: () => number;
}
export const useCartStore = create<CartStore>()(
persist(
(set, get) => ({
items: [],
total: 0,
addItem: (item) => set((state) => {
const existingItem = state.items.find(i => i.id === item.id);
if (existingItem) {
return {
items: state.items.map(i =>
i.id === item.id
? { ...i, quantity: i.quantity + 1 }
: i
),
total: state.total + item.price
};
}
return {
items: [...state.items, { ...item, quantity: 1 }],
total: state.total + item.price
};
}),
removeItem: (id) => set((state) => {
const item = state.items.find(i => i.id === id);
if (!item) return state;
return {
items: state.items.filter(i => i.id !== id),
total: state.total - (item.price * item.quantity)
};
}),
updateQuantity: (id, quantity) => set((state) => {
const item = state.items.find(i => i.id === id);
if (!item) return state;
const diff = quantity - item.quantity;
if (quantity === 0) {
return {
items: state.items.filter(i => i.id !== id),
total: state.total - (item.price * item.quantity)
};
}
return {
items: state.items.map(i =>
i.id === id ? { ...i, quantity } : i
),
total: state.total + (item.price * diff)
};
}),
clearCart: () => set({ items: [], total: 0 }),
getItemCount: () => get().items.reduce((sum, item) => sum + item.quantity, 0)
}),
{
name: 'shopping-cart',
}
)
);
Security Best Practices
Content Security Policy
// next.config.js
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
img-src 'self' data: https: blob:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.yourwebsite.com;
frame-ancestors 'none';
base-uri 'self';
form-action 'self';
`.replace(/\s{2,}/g, ' ').trim()
},
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
},
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'Referrer-Policy',
value: 'origin-when-cross-origin'
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()'
}
];
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: securityHeaders,
},
];
},
};
Input Sanitization
// lib/validation.ts
import DOMPurify from 'isomorphic-dompurify';
import { z } from 'zod';
export const sanitizeHTML = (dirty: string): string => {
return DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],
ALLOWED_ATTR: ['href', 'title', 'target']
});
};
export const contactFormSchema = z.object({
name: z.string()
.min(2, 'Name must be at least 2 characters')
.max(50, 'Name must be less than 50 characters')
.regex(/^[a-zA-Z\s]+$/, 'Name can only contain letters and spaces'),
email: z.string()
.email('Invalid email address')
.toLowerCase(),
phone: z.string()
.regex(/^\+?[1-9]\d{1,14}$/, 'Invalid phone number')
.optional(),
message: z.string()
.min(10, 'Message must be at least 10 characters')
.max(1000, 'Message must be less than 1000 characters')
.transform(sanitizeHTML),
website: z.string().url().optional(),
});
export type ContactFormData = z.infer<typeof contactFormSchema>;
Performance Monitoring
// lib/analytics.ts
export class PerformanceMonitor {
static measurePageLoad() {
if (typeof window === 'undefined') return;
window.addEventListener('load', () => {
const perfData = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
const metrics = {
// Core Web Vitals
FCP: this.getFCP(),
LCP: this.getLCP(),
FID: this.getFID(),
CLS: this.getCLS(),
// Other metrics
TTFB: perfData.responseStart - perfData.requestStart,
domContentLoaded: perfData.domContentLoadedEventEnd - perfData.domContentLoadedEventStart,
loadComplete: perfData.loadEventEnd - perfData.loadEventStart,
// Resource timing
resourceCount: performance.getEntriesByType('resource').length,
transferSize: this.getTotalTransferSize(),
};
this.sendToAnalytics(metrics);
});
}
static getFCP(): number {
const fcp = performance.getEntriesByName('first-contentful-paint')[0];
return fcp ? fcp.startTime : 0;
}
static getLCP(): Promise<number> {
return new Promise((resolve) => {
new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1] as any;
resolve(lastEntry.renderTime || lastEntry.loadTime);
}).observe({ entryTypes: ['largest-contentful-paint'] });
});
}
static getFID(): Promise<number> {
return new Promise((resolve) => {
new PerformanceObserver((entryList) => {
const firstInput = entryList.getEntries()[0] as any;
resolve(firstInput.processingStart - firstInput.startTime);
}).observe({ entryTypes: ['first-input'] });
});
}
static getCLS(): Promise<number> {
return new Promise((resolve) => {
let clsValue = 0;
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries() as any[]) {
if (!entry.hadRecentInput) {
clsValue += entry.value;
}
}
resolve(clsValue);
}).observe({ entryTypes: ['layout-shift'] });
});
}
static getTotalTransferSize(): number {
const resources = performance.getEntriesByType('resource') as PerformanceResourceTiming[];
return resources.reduce((total, resource) => total + resource.transferSize, 0);
}
static sendToAnalytics(metrics: any) {
// Send to your analytics service
console.log('Performance Metrics:', metrics);
// fetch('/api/analytics/performance', {
// method: 'POST',
// body: JSON.stringify(metrics)
// });
}
}
Database Optimization
Prisma Schema with Indexes
// prisma/schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["fullTextSearch"]
}
model User {
id String @id @default(cuid())
email String @unique
name String
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
orders Order[]
reviews Review[]
@@index([email])
@@index([createdAt])
}
model Product {
id String @id @default(cuid())
slug String @unique
name String
description String @db.Text
price Decimal @db.Decimal(10, 2)
stock Int @default(0)
published Boolean @default(false)
categoryId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
category Category @relation(fields: [categoryId], references: [id])
images Image[]
reviews Review[]
orderItems OrderItem[]
@@index([slug])
@@index([categoryId])
@@index([published, createdAt])
@@fulltext([name, description])
}
model Category {
id String @id @default(cuid())
slug String @unique
name String
products Product[]
@@index([slug])
}
model Order {
id String @id @default(cuid())
userId String
total Decimal @db.Decimal(10, 2)
status OrderStatus @default(PENDING)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id])
items OrderItem[]
@@index([userId])
@@index([status, createdAt])
}
model OrderItem {
id String @id @default(cuid())
orderId String
productId String
quantity Int
price Decimal @db.Decimal(10, 2)
order Order @relation(fields: [orderId], references: [id])
product Product @relation(fields: [productId], references: [id])
@@index([orderId])
@@index([productId])
}
enum OrderStatus {
PENDING
PROCESSING
SHIPPED
DELIVERED
CANCELLED
}
Optimized Queries
// lib/db/queries.ts
import { prisma } from '@/lib/prisma';
export async function getProductsWithPagination(
page: number = 1,
limit: number = 20,
categorySlug?: string
) {
const skip = (page - 1) * limit;
const where = categorySlug
? {
published: true,
category: { slug: categorySlug }
}
: { published: true };
const [products, total] = await prisma.$transaction([
prisma.product.findMany({
where,
skip,
take: limit,
select: {
id: true,
slug: true,
name: true,
price: true,
stock: true,
images: {
take: 1,
select: {
url: true,
alt: true
}
},
_count: {
select: { reviews: true }
}
},
orderBy: {
createdAt: 'desc'
}
}),
prisma.product.count({ where })
]);
return {
products,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit)
}
};
}
export async function getProductBySlug(slug: string) {
return prisma.product.findUnique({
where: { slug },
include: {
category: true,
images: true,
reviews: {
take: 5,
orderBy: { createdAt: 'desc' },
include: {
user: {
select: {
name: true
}
}
}
},
_count: {
select: { reviews: true }
}
}
});
}
export async function searchProducts(query: string, limit: number = 10) {
return prisma.product.findMany({
where: {
published: true,
OR: [
{
name: {
contains: query,
mode: 'insensitive'
}
},
{
description: {
contains: query,
mode: 'insensitive'
}
}
]
},
take: limit,
select: {
id: true,
slug: true,
name: true,
price: true
}
});
}
Testing Strategy
Unit Testing with Vitest
// __tests__/utils/formatPrice.test.ts
import { describe, it, expect } from 'vitest';
import { formatPrice } from '@/lib/utils';
describe('formatPrice', () => {
it('formats price correctly', () => {
expect(formatPrice(1234.56)).toBe('$1,234.56');
expect(formatPrice(0)).toBe('$0.00');
expect(formatPrice(999.99)).toBe('$999.99');
});
it('handles different currencies', () => {
expect(formatPrice(1000, 'EUR')).toBe('€1,000.00');
expect(formatPrice(1000, 'GBP')).toBe('£1,000.00');
});
it('handles decimal places', () => {
expect(formatPrice(10.5)).toBe('$10.50');
expect(formatPrice(10.999)).toBe('$11.00');
});
});
Integration Testing with Playwright
// e2e/checkout.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Checkout Flow', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
});
test('complete purchase flow', async ({ page }) => {
// Add product to cart
await page.click('[data-testid="product-1"]');
await page.click('[data-testid="add-to-cart"]');
// Verify cart badge updates
await expect(page.locator('[data-testid="cart-count"]')).toHaveText('1');
// Go to cart
await page.click('[data-testid="cart-button"]');
await expect(page).toHaveURL('/cart');
// Proceed to checkout
await page.click('[data-testid="checkout-button"]');
// Fill shipping information
await page.fill('[name="name"]', 'John Doe');
await page.fill('[name="email"]', 'john@example.com');
await page.fill('[name="address"]', '123 Main St');
await page.fill('[name="city"]', 'New York');
await page.fill('[name="zip"]', '10001');
// Fill payment information (test mode)
await page.fill('[name="cardNumber"]', '4242424242424242');
await page.fill('[name="expiry"]', '12/25');
await page.fill('[name="cvc"]', '123');
// Submit order
await page.click('[data-testid="place-order"]');
// Verify success
await expect(page).toHaveURL(/\/orders\/[a-z0-9]+/);
await expect(page.locator('[data-testid="order-success"]')).toBeVisible();
});
test('handles out of stock products', async ({ page }) => {
await page.goto('/products/out-of-stock-item');
const addButton = page.locator('[data-testid="add-to-cart"]');
await expect(addButton).toBeDisabled();
await expect(page.locator('[data-testid="out-of-stock"]')).toBeVisible();
});
});
Deployment and CI/CD
GitHub Actions Workflow
# .github/workflows/deploy.yml
name: Deploy to Production
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
NODE_VERSION: '20.x'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run type check
run: npm run type-check
- name: Run unit tests
run: npm run test:unit
- name: Run E2E tests
run: npm run test:e2e
env:
DATABASE_URL: ${{ secrets.TEST_DATABASE_URL }}
- name: Build
run: npm run build
env:
NEXT_PUBLIC_API_URL: ${{ secrets.API_URL }}
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- name: Deploy to Vercel
uses: amondnet/vercel-action@v20
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-args: '--prod'
Conclusion
Building high-performance websites in 2025 requires a comprehensive approach that balances modern technology, best practices, and business objectives. Success lies in:
- Choosing the right tech stack based on project requirements
- Optimizing performance at every level from code to infrastructure
- Implementing SEO best practices for discoverability
- Ensuring security through multiple layers of protection
- Testing thoroughly to catch issues before production
- Monitoring continuously to maintain and improve performance
The websites that succeed are those built with scalability, performance, and user experience as core principles from day one.
Looking to build a high-performance website that drives business results? TezCraft specializes in developing modern, scalable websites using cutting-edge technologies like React, Next.js, Vue.js, and more. Our expert development team creates lightning-fast, SEO-optimized websites that convert visitors into customers. From responsive design and progressive web apps to complex e-commerce platforms and enterprise web applications, we deliver solutions that combine exceptional performance with stunning user experiences. Contact us today to discuss your website development project and discover how we can help your business grow online.
Top comments (1)
This post underscores the importance of balancing performance, SEO, and UX in building modern web apps.