Deploying a Preact App
Preact is a fast, lightweight alternative to React that delivers the same modern component-based API with a dramatically smaller footprint. At just 3KB, Preact enables you to build high-performance single-page applications (SPAs), progressive web apps (PWAs), and dynamic web experiences with minimal JavaScript overhead. Its compatibility layer means you can share components with React, use most React libraries, and achieve exceptional performance on all devices—from powerful desktops to resource-constrained mobile phones. Preact’s small size translates to faster downloads, quicker parsing, and snappier interactions, making it ideal for performance-critical applications where every kilobyte matters.
This comprehensive guide walks through deploying a Preact application to Klutch.sh using either Nixpacks (automatic zero-configuration deployment) or a Dockerfile (manual container control). You’ll learn how to set up a Preact project with Vite, create components, manage state with hooks, integrate APIs, optimize builds, configure environment variables, implement security best practices, set up monitoring, configure custom domains, and troubleshoot common issues. By the end of this guide, you’ll have a production-ready Preact application running on Klutch.sh’s global infrastructure with automatic HTTPS, optimized performance, and reliable hosting.
Prerequisites
- Node.js & npm (version 18+, required) – Download Node.js
- Git installed locally and a GitHub account (Klutch.sh uses GitHub as the only git source)
- Klutch.sh account with access to the dashboard at klutch.sh/app
- Basic knowledge of JavaScript, HTML, and CSS
- Text editor or IDE for code editing (VS Code recommended)
Getting Started: Create a Preact App
1. Create a New Preact Project
Use Vite to create a new Preact project with optimal tooling and fast development experience:
npm create vite@latest my-preact-app -- --template preactcd my-preact-appnpm install2. Project Structure
A typical Preact application structure looks like:
my-preact-app/├── src/│ ├── components/│ │ ├── Counter.jsx│ │ ├── Header.jsx│ │ ├── Footer.jsx│ │ └── Card.jsx│ ├── pages/│ │ ├── Home.jsx│ │ ├── About.jsx│ │ └── Dashboard.jsx│ ├── hooks/│ │ ├── useApi.js│ │ ├── useFetch.js│ │ └── useLocalStorage.js│ ├── services/│ │ ├── api.js│ │ └── auth.js│ ├── styles/│ │ ├── index.css│ │ └── components.css│ ├── App.jsx│ └── main.jsx├── index.html├── vite.config.js├── package.json├── .env.example├── README.md└── Dockerfile3. Install and Run Locally
Install dependencies and start the development server:
npm installnpm run devYour Preact app will be available at http://localhost:5173. The Vite development server provides hot module replacement (HMR) for instant updates as you code.
4. Create Your First Component
Create src/components/Counter.jsx:
import { useState } from 'preact/hooks';
export function Counter() { const [count, setCount] = useState(0);
return ( <div style={{ padding: '2rem', textAlign: 'center', border: '1px solid #ddd', borderRadius: '8px', marginBottom: '2rem' }}> <h2>Counter Demo</h2> <p style={{ fontSize: '2rem', margin: '1rem 0' }}>{count}</p> <button onClick={() => setCount(count + 1)} style={{ padding: '0.5rem 1rem', marginRight: '0.5rem', backgroundColor: '#667eea', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }} > Increment </button> <button onClick={() => setCount(count - 1)} style={{ padding: '0.5rem 1rem', backgroundColor: '#e74c3c', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }} > Decrement </button> </div> );}5. Create a Header Component
Create src/components/Header.jsx:
import { Fragment } from 'preact';
export function Header({ title = 'My Preact App' }) { return ( <Fragment> <header style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', color: 'white', padding: '2rem', textAlign: 'center', marginBottom: '2rem' }}> <h1>{title}</h1> <p>Deployed on Klutch.sh</p> </header> </Fragment> );}6. Update App.jsx
Update src/App.jsx to use your components:
import { useState } from 'preact/hooks';import './App.css';import { Counter } from './components/Counter';import { Header } from './components/Header';
export function App() { const [activeTab, setActiveTab] = useState('home');
return ( <div> <Header title="Preact on Klutch.sh" />
<nav style={{ display: 'flex', gap: '1rem', padding: '1rem', background: '#f5f5f5', borderBottom: '1px solid #ddd', marginBottom: '2rem' }}> <button onClick={() => setActiveTab('home')} style={{ padding: '0.5rem 1rem', background: activeTab === 'home' ? '#667eea' : '#fff', color: activeTab === 'home' ? 'white' : '#333', border: 'none', borderRadius: '4px', cursor: 'pointer' }} > Home </button> <button onClick={() => setActiveTab('demo')} style={{ padding: '0.5rem 1rem', background: activeTab === 'demo' ? '#667eea' : '#fff', color: activeTab === 'demo' ? 'white' : '#333', border: 'none', borderRadius: '4px', cursor: 'pointer' }} > Demo </button> </nav>
<main style={{ maxWidth: '1200px', margin: '0 auto', padding: '0 1rem' }}> {activeTab === 'home' && ( <section> <h2>Welcome to Preact</h2> <p>Preact is a fast, lightweight alternative to React with the same modern API.</p> <ul> <li>⚡ Just 3KB and extremely fast</li> <li>🎯 Same component model as React</li> <li>📱 Perfect for mobile and PWAs</li> <li>🔗 Seamless third-party integration</li> </ul> </section> )}
{activeTab === 'demo' && ( <section> <Counter /> </section> )} </main>
<footer style={{ background: '#2c3e50', color: 'white', padding: '2rem', textAlign: 'center', marginTop: '3rem' }}> <p>© 2024 My Preact App. Deployed on Klutch.sh.</p> </footer> </div> );}7. Create Custom Hooks
Create src/hooks/useApi.js for API data fetching:
import { useState, useEffect } from 'preact/hooks';
export function useApi(url, options = {}) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null);
useEffect(() => { async function fetchData() { try { setLoading(true); const response = await fetch(url, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers } });
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
const result = await response.json(); setData(result); setError(null); } catch (err) { setError(err.message); setData(null); } finally { setLoading(false); } }
if (url) { fetchData(); } }, [url]);
return { data, loading, error };}8. Create API Service
Create src/services/api.js for centralized API communication:
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000';
export const api = { get: async (endpoint) => { const response = await fetch(`${API_BASE_URL}${endpoint}`, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token') || ''}` } }); if (!response.ok) throw new Error(`API error: ${response.status}`); return response.json(); },
post: async (endpoint, data) => { const response = await fetch(`${API_BASE_URL}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token') || ''}` }, body: JSON.stringify(data) }); if (!response.ok) throw new Error(`API error: ${response.status}`); return response.json(); },
put: async (endpoint, data) => { const response = await fetch(`${API_BASE_URL}${endpoint}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token') || ''}` }, body: JSON.stringify(data) }); if (!response.ok) throw new Error(`API error: ${response.status}`); return response.json(); },
delete: async (endpoint) => { const response = await fetch(`${API_BASE_URL}${endpoint}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${localStorage.getItem('token') || ''}` } }); if (!response.ok) throw new Error(`API error: ${response.status}`); return response.json(); }};9. Configure Vite
Update vite.config.js for optimal Preact configuration:
import { defineConfig } from 'vite';import preact from '@preactjs/preset-vite';
export default defineConfig({ plugins: [preact()], server: { port: 5173, strictPort: false }, build: { target: 'esnext', minify: 'terser', cssCodeSplit: true, rollupOptions: { output: { manualChunks: { 'vendor': ['preact', 'preact/hooks'] } } } }});10. Create Environment Variables
Create .env.example:
VITE_API_URL=http://localhost:3000VITE_APP_NAME=My Preact AppVITE_ANALYTICS_ID=VITE_ENABLE_DEBUG=false11. Build Optimization
Create a production build with optimizations:
npm run buildThis creates an optimized, minified bundle in the dist/ directory ready for production deployment. Preact will be tree-shaken and minified to its smallest size.
12. Test Production Build Locally
Serve the production build locally:
npm install -g http-serverhttp-server dist -p 8000Visit http://localhost:8000 to test your production build.
Local Production Build Test
Before deploying, test your application in a production-like environment:
# Build for productionnpm run build
# Serve the production buildhttp-server dist -p 8000 --gzipVerify that:
- All pages load correctly
- Interactive components work as expected
- API calls function properly
- Performance metrics are acceptable
- No console errors appear in DevTools
- Mobile responsiveness is correct
- Forms submit successfully
Deploying with Nixpacks
Nixpacks automatically detects your Preact application and configures build and runtime environments without requiring a Dockerfile. This is the simplest deployment method for Preact apps.
Prerequisites for Nixpacks Deployment
- Your Preact project pushed to a GitHub repository
- Valid
package.jsonwith build and start scripts - No
Dockerfilein the repository root (if one exists, Klutch.sh will use Docker instead)
Steps to Deploy with Nixpacks
-
Push Your Preact App to GitHub
Initialize and push your project to GitHub:
Terminal window git initgit add .git commit -m "Initial Preact app"git branch -M maingit remote add origin git@github.com:YOUR_USERNAME/YOUR_REPO.gitgit push -u origin main -
Log In to Klutch.sh Dashboard
Go to klutch.sh/app and sign in with your GitHub account.
-
Create a Project
Navigate to the Projects section and create a new project for your Preact app.
-
Create an App
Click “Create App” and select your GitHub repository.
-
Select the Branch
Choose the branch you want to deploy (typically
main). -
Configure Traffic Type
Select HTTP as the traffic type for Preact (a web application serving HTML/CSS/JS).
-
Set the Internal Port
Set the internal port to
3000– this is the port where Nixpacks will serve your Preact app using a production HTTP server. -
Add Environment Variables (Optional)
Add any environment variables your Preact app requires:
VITE_API_URL=https://api.example.comVITE_APP_NAME=My Preact AppVITE_ANALYTICS_ID=your-analytics-idNODE_ENV=productionIf you need to customize the Nixpacks build or start command, use these environment variables:
BUILD_COMMAND: Override the default build command (e.g.,npm run build)START_COMMAND: Override the default start command (e.g.,http-server dist -p 3000)
-
Configure Compute Resources
Select your region, compute size, and number of instances based on expected traffic.
-
Deploy
Click “Create” to start the deployment. Nixpacks will automatically build and deploy your Preact app. Your app will be available at a URL like
https://example-app.klutch.sh.
Deploying with Docker
For more control over your deployment environment, you can use a Dockerfile. Klutch.sh automatically detects a Dockerfile in your repository root and uses it for deployment.
Creating a Dockerfile for Preact
Create a Dockerfile in the root of your Preact project:
# === Build stage ===FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./RUN npm install
COPY . .RUN npm run build
# === Production stage ===FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
# Configure Nginx for Preact SPARUN echo 'server { \ listen 80; \ server_name _; \ root /usr/share/nginx/html; \ index index.html index.htm; \ \ location / { \ try_files $uri $uri/ /index.html; \ } \ \ location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { \ expires 1y; \ add_header Cache-Control "public, immutable"; \ } \}' > /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]Alternative Dockerfile Using Node.js http-server
For a lightweight alternative using Node.js http-server:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./RUN npm install
COPY . .RUN npm run build
ENV PORT=3000EXPOSE 3000
CMD ["npx", "http-server", "dist", "-p", "3000", "--gzip"]Dockerfile Notes
- Build stage: Installs dependencies and builds your Preact app with Vite.
- Production stage: Uses Nginx (recommended for SPAs) or http-server to serve your static files.
- Port: The
PORTenvironment variable is set to3000for http-server or80for Nginx. - Multi-stage build: Reduces final image size by excluding Node.js and build tools from the runtime container.
- SPA routing: The Nginx configuration includes
try_files $uri $uri/ /index.htmlfor proper client-side routing. - Caching headers: Nginx configuration includes long-term caching for static assets.
Steps to Deploy with Docker
-
Create a Dockerfile
Add the Dockerfile (shown above) to the root of your Preact repository.
-
Test Locally (Optional)
Build and test the Docker image locally:
Terminal window docker build -t preact-app:latest .docker run -p 3000:80 preact-app:latestVisit http://localhost:3000 to verify.
-
Push to GitHub
Commit and push the Dockerfile and your code:
Terminal window git add Dockerfilegit commit -m "Add Dockerfile for production deployment"git push origin main -
Create an App in Klutch.sh
Go to klutch.sh/app, navigate to “Create App”, and select your repository.
-
Configure the App
- Traffic Type: Select HTTP
- Internal Port: Set to
80(Nginx) or3000(http-server) - Environment Variables: Add any required runtime variables
-
Deploy
Klutch.sh automatically detects the Dockerfile and uses it to build and deploy your app. Your app will be available at
https://example-app.klutch.sh.
Environment Variables
Define environment variables in the Klutch.sh dashboard for production configuration:
VITE_API_URL=https://api.example.comVITE_APP_NAME=My Preact AppVITE_ANALYTICS_ID=your-analytics-idNODE_ENV=productionAccessing Environment Variables
Access environment variables in your Preact app through Vite’s import.meta.env:
// In your components or servicesconst apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3000';const appName = import.meta.env.VITE_APP_NAME || 'My App';const analyticsId = import.meta.env.VITE_ANALYTICS_ID || '';const isDev = import.meta.env.DEV;const isProd = import.meta.env.PROD;
// Usage exampleexport function App() { return ( <div> <h1>{appName}</h1> <p>Running in {isProd ? 'production' : 'development'}</p> </div> );}Building with Custom Environment Variables
Ensure environment variables are prefixed with VITE_ to be available in the browser:
VITE_API_URL=https://api.example.com npm run buildPersistent Storage
If your Preact app generates files, caches data, or needs to store user-generated content on the server, you can use persistent volumes in Klutch.sh.
Adding Persistent Volumes
- In the Klutch.sh dashboard, go to your app’s Volumes section.
- Click Add Volume.
- Set the mount path (e.g.,
/data,/uploads,/cache). - Set the size (e.g.,
1 GiB,5 GiB). - Save and redeploy your app.
Example: Using localStorage with Server Sync
// Sync browser localStorage with serverfunction syncDataToServer() { const userData = localStorage.getItem('userData'); if (userData) { api.post('/api/user-data', JSON.parse(userData)) .then(() => console.log('Data synced')) .catch(err => console.error('Sync failed:', err)); }}
import { useEffect } from 'preact/hooks';
export function App() { useEffect(() => { window.addEventListener('beforeunload', syncDataToServer); return () => window.removeEventListener('beforeunload', syncDataToServer); }, []);
// Rest of component}Security Best Practices
1. HTTPS/SSL Enforcement
Klutch.sh automatically provides HTTPS for all deployed apps. All traffic is encrypted and secure by default.
2. Content Security Policy
Implement CSP headers to protect against XSS attacks. Configure in Nginx:
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;" always;3. Protect Against CSRF
Use CSRF tokens for forms and API requests:
// Get CSRF token from meta tag or local storageconst csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || localStorage.getItem('csrf-token');
// Add to API requestsexport const api = { post: async (endpoint, data) => { const response = await fetch(`${API_BASE_URL}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken || '' }, body: JSON.stringify(data) }); return response.json(); }};4. Input Validation and Sanitization
Always validate and sanitize user input:
// Validate emailfunction validateEmail(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email);}
// Sanitize HTML inputfunction sanitizeInput(input) { const div = document.createElement('div'); div.textContent = input; return div.innerHTML;}
// Usage in componentexport function ContactForm() { const [email, setEmail] = useState(''); const [error, setError] = useState('');
const handleSubmit = (e) => { e.preventDefault(); if (!validateEmail(email)) { setError('Invalid email address'); return; } // Submit form };
return ( <form onSubmit={handleSubmit}> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required /> {error && <p style={{ color: 'red' }}>{error}</p>} <button type="submit">Submit</button> </form> );}5. Secure API Communication
Always use HTTPS for API calls and include authentication tokens:
export const api = { baseURL: 'https://api.example.com', // Always HTTPS in production
request: async (method, endpoint, data) => { const token = localStorage.getItem('authToken'); const response = await fetch(`${api.baseURL}${endpoint}`, { method, headers: { 'Content-Type': 'application/json', 'Authorization': token ? `Bearer ${token}` : '' }, body: data ? JSON.stringify(data) : null });
if (response.status === 401) { // Handle unauthorized - redirect to login window.location.href = '/login'; }
return response.json(); }};6. Environment Variable Security
Never commit sensitive data to git. Use environment variables:
// ✗ WRONG - Don't hardcode secretsconst apiKey = 'sk_live_abc123...';
// ✓ CORRECT - Use environment variablesconst apiKey = import.meta.env.VITE_API_KEY;
// Never expose secrets in client-side code// For sensitive operations, call a backend API instead7. Dependency Security
Keep dependencies updated and audit for vulnerabilities:
npm outdatednpm auditnpm audit fixnpm updateMonitoring and Logging
Performance Monitoring
Monitor Preact app performance using Web Vitals:
import { useState, useEffect } from 'preact/hooks';
export function App() { useEffect(() => { // Measure Largest Contentful Paint (LCP) const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { console.log('LCP:', entry.renderTime || entry.loadTime);
if (import.meta.env.PROD) { // Send to analytics service fetch('/api/metrics', { method: 'POST', body: JSON.stringify({ metric: 'LCP', value: entry.renderTime || entry.loadTime }) }); } } });
observer.observe({ entryTypes: ['largest-contentful-paint'] });
// Cleanup return () => observer.disconnect(); }, []);
return <div>...</div>;}Error Tracking
Implement global error handling:
export function setupErrorTracking() { window.addEventListener('error', (event) => { console.error('Global error:', event.error);
if (import.meta.env.PROD) { api.post('/api/errors', { message: event.message, stack: event.error?.stack, url: window.location.href, timestamp: new Date().toISOString() }); } });
window.addEventListener('unhandledrejection', (event) => { console.error('Unhandled promise rejection:', event.reason);
if (import.meta.env.PROD) { api.post('/api/errors', { message: event.reason?.message, stack: event.reason?.stack, type: 'unhandledRejection', url: window.location.href, timestamp: new Date().toISOString() }); } });}Analytics Integration
Add analytics tracking to monitor user behavior:
export function useAnalytics() { useEffect(() => { // Google Analytics window.gtag?.('config', 'GA_ID', { page_path: window.location.pathname, page_title: document.title });
// Track custom events const trackEvent = (eventName, eventData) => { window.gtag?.('event', eventName, eventData); };
window.trackEvent = trackEvent; }, []);}Custom Domains
To use a custom domain with your Klutch.sh-deployed Preact app:
1. Add the Domain in Klutch.sh
In the Klutch.sh dashboard, go to your app’s settings and add your custom domain (e.g., app.example.com).
2. Update Your DNS Provider
Update your DNS records with the CNAME provided by Klutch.sh:
CNAME: app.example.com → example-app.klutch.sh3. Update Your Preact App
Update API endpoints if needed:
// API configurationexport const API_BASE_URL = import.meta.env.VITE_API_URL || (window.location.hostname.includes('localhost') ? 'http://localhost:3000' : 'https://api.example.com');4. Wait for DNS Propagation
DNS changes can take up to 48 hours to propagate. Verify with:
nslookup app.example.com# ordig app.example.com CNAMEOnce propagated, your Preact app will be accessible at your custom domain with automatic HTTPS.
Troubleshooting
Issue 1: Build Fails with “Module not found”
Error: Cannot find module 'preact' or similar
Solutions:
- Run
npm installto ensure all dependencies are installed - Check that
package.jsonincludes preact and @preactjs/preset-vite - Delete
node_modulesandpackage-lock.json, then runnpm installagain - Verify file paths are correct (case-sensitive on Linux)
Issue 2: Routing Not Working
Error: 404 on page refresh or bookmarked URLs
Solutions:
- Ensure Nginx configuration includes
try_files $uri $uri/ /index.html;for SPA routing - Check that your router is configured correctly (preact-router or similar)
- Verify the internal port is set correctly in Klutch.sh dashboard
- Test locally with production build:
npm run build && http-server dist
Issue 3: Environment Variables Not Available
Error: import.meta.env.VITE_API_URL is undefined
Solutions:
- Ensure environment variables are prefixed with
VITE_for browser access - Rebuild after adding new environment variables
- Check that variables are set in Klutch.sh dashboard (refresh if needed)
- Test locally with
.envfile:VITE_API_URL=http://localhost:3000 npm run dev - For Node.js-only variables, use
process.env(these won’t work in browser)
Issue 4: API Requests Failing (CORS)
Error: CORS error or 401 Unauthorized
Solutions:
- Ensure API URL is correct (check environment variables)
- Verify CORS headers on backend API server
- Check that authentication token is being sent:
headers: {'Authorization': `Bearer ${localStorage.getItem('authToken')}`}
- Use relative URLs if calling same-origin API:
/api/usersinstead of full URL
Issue 5: Performance Issues
Error: Slow initial load or janky animations
Solutions:
- Check bundle size with Vite analysis plugin
- Enable code splitting in
vite.config.js:build: {rollupOptions: {output: {manualChunks: {'vendor': ['preact', 'preact/hooks']}}}} - Optimize images and assets
- Use lazy loading for routes:
import { lazy } from 'preact/compat';const Dashboard = lazy(() => import('./pages/Dashboard'));
- Profile with browser DevTools (Performance tab)
Issue 6: Blank Page on Production
Error: App shows blank page or white screen
Solutions:
- Check browser console for JavaScript errors
- Verify
index.htmlis being served correctly - Check that Nginx/http-server is configured correctly
- Ensure build completed successfully: check for
/distfolder - Test production build locally before deploying
- Clear browser cache (Ctrl+Shift+Delete)
Issue 7: Hot Module Replacement (HMR) Not Working
Error: Changes don’t reflect during development
Solutions:
- HMR only works in development mode (
npm run dev) - Ensure Vite dev server is running on the correct port
- Check firewall settings if developing remotely
- Restart dev server if issues persist
- Check Vite config for HMR settings
Best Practices
1. Component Organization
Organize components by feature or page:
src/components/ ├── common/ │ ├── Header.jsx │ ├── Footer.jsx │ └── Navigation.jsx ├── dashboard/ │ ├── DashboardLayout.jsx │ ├── StatsCard.jsx │ └── Chart.jsx └── auth/ ├── LoginForm.jsx └── RegisterForm.jsx2. Use Hooks for State Management
Leverage Preact hooks for simple state or Context API for complex state:
import { createContext } from 'preact';import { useContext, useState } from 'preact/hooks';
const UserContext = createContext();
export function UserProvider({ children }) { const [user, setUser] = useState(null);
return ( <UserContext.Provider value={{ user, setUser }}> {children} </UserContext.Provider> );}
export function useUser() { return useContext(UserContext);}3. Lazy Load Routes
Split code by route for faster initial loads:
import { lazy, Suspense } from 'preact/compat';
const Home = lazy(() => import('./pages/Home'));const Dashboard = lazy(() => import('./pages/Dashboard'));const Settings = lazy(() => import('./pages/Settings'));
export function App() { return ( <Suspense fallback={<Loading />}> <Router> <Route path="/" component={Home} /> <Route path="/dashboard" component={Dashboard} /> <Route path="/settings" component={Settings} /> </Router> </Suspense> );}4. Optimize Rendering
Use memoization to prevent unnecessary re-renders:
import { memo } from 'preact/compat';
const ExpensiveComponent = memo(({ data }) => { return <div>{data.name}</div>;});5. Handle Loading States
Always provide feedback during data loading:
export function UserList() { const { data, loading, error } = useApi('/api/users');
if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; if (!data) return <div>No data</div>;
return ( <ul> {data.map(user => <li key={user.id}>{user.name}</li>)} </ul> );}6. Use Semantic HTML
Write accessible HTML for better SEO and UX:
// ✓ Good - semantic HTMLexport function Card({ title, content }) { return ( <article> <h2>{title}</h2> <p>{content}</p> </article> );}
// ✗ Avoid - non-semantic divsexport function Card({ title, content }) { return ( <div> <div>{title}</div> <div>{content}</div> </div> );}7. Test Your Components
Write unit tests for critical components:
import { render } from '@testing-library/preact';import { Counter } from './Counter';
test('Counter increments', () => { const { container } = render(<Counter />); const button = container.querySelector('button'); button.click(); // Assert counter incremented});8. Document Your Components
Add JSDoc comments for clarity:
/** * Displays a list of users * @param {Array} users - Array of user objects * @param {Function} onSelect - Callback when user is selected * @returns {VNode} The rendered component */export function UserList({ users, onSelect }) { return ( <ul> {users.map(user => ( <li key={user.id} onClick={() => onSelect(user)}> {user.name} </li> ))} </ul> );}9. Monitor Build Size
Keep your bundle size optimized:
npm install --save-dev vite-plugin-visualizerAdd to vite.config.js:
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({ plugins: [ preact(), visualizer() ]});10. Keep Dependencies Updated
Regularly update Preact and dependencies:
npm outdatednpm updatenpm audit fixVerifying Your Deployment
After deployment completes:
- Check the App URL: Visit your app at
https://example-app.klutch.shor your custom domain. - Test Interactivity: Click buttons, navigate routes, and submit forms.
- Check Console: Open F12 and verify no errors appear.
- Test API Integration: Verify API calls work and return expected data.
- Check Performance: Use Google PageSpeed Insights to verify performance metrics.
- Test Responsiveness: Verify mobile, tablet, and desktop layouts work.
- Monitor Logs: Check the Klutch.sh dashboard logs for any issues.
If your app doesn’t work as expected, review the troubleshooting section and check the Klutch.sh dashboard logs for detailed error messages.
External Resources
- Official Preact Documentation
- Vite Documentation
- Klutch.sh Official Website
- MDN JavaScript Documentation
- Frontend Development Basics
- Web Performance Best Practices
- Web Security Documentation
Deploying a Preact app to Klutch.sh is straightforward with Nixpacks for automatic deployment or Docker for custom environments. By following this guide, you’ve learned how to create a Preact project with Vite, build performant components, manage state with hooks, integrate APIs, optimize builds, configure environment variables, implement security best practices, set up monitoring, and troubleshoot common issues. Your Preact application is now running on Klutch.sh’s global infrastructure with automatic HTTPS, optimized performance, and reliable hosting. For additional help or questions, consult the official Preact documentation or contact Klutch.sh support.