Skip to content

Deploying a Vue App

Vue is a progressive JavaScript framework for building user interfaces with an approachable, performant, and versatile ecosystem. Vue’s gentle learning curve, reactive data binding, and powerful templating syntax make it perfect for developers of all skill levels. Whether you’re building simple interactive components, full-featured single-page applications (SPAs), or complex progressive web apps (PWAs), Vue provides the flexibility and power you need. With Vue 3’s composition API, first-class TypeScript support, and a mature ecosystem including Vue Router and Pinia for state management, Vue scales effortlessly from small projects to large enterprise applications.

This comprehensive guide walks through deploying a Vue 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 Vue project, create and compose components, manage state with the composition API and Pinia, integrate with external 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 Vue application running on Klutch.sh’s global infrastructure with automatic HTTPS, optimized performance, and reliable hosting.

Prerequisites

  • Node.js & npm (version 16+, 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 Vue App

1. Create a New Vue Project

Create a new Vue application using the official create-vue tool:

Terminal window
npm create vue@latest

Select the following options when prompted:

  • Add TypeScript (optional but recommended)
  • Add Router for navigation
  • Add Pinia for state management
  • Add ESLint and Prettier for code quality

Or use the quick start:

Terminal window
npm create vue@latest my-vue-app -- --typescript --router --pinia
cd my-vue-app
npm install

2. Project Structure

A typical Vue application structure looks like:

my-vue-app/
├── src/
│ ├── components/
│ │ ├── Header.vue
│ │ ├── Footer.vue
│ │ ├── Counter.vue
│ │ ├── Card.vue
│ │ └── Button.vue
│ ├── views/
│ │ ├── HomeView.vue
│ │ ├── AboutView.vue
│ │ ├── DashboardView.vue
│ │ └── ProfileView.vue
│ ├── stores/
│ │ ├── auth.js
│ │ ├── user.js
│ │ └── theme.js
│ ├── services/
│ │ ├── api.js
│ │ ├── auth.js
│ │ └── http.js
│ ├── composables/
│ │ ├── useApi.js
│ │ ├── useFetch.js
│ │ └── useLocalStorage.js
│ ├── assets/
│ │ ├── main.css
│ │ ├── base.css
│ │ └── logo.svg
│ ├── router/
│ │ └── index.js
│ ├── App.vue
│ └── main.js
├── public/
│ ├── favicon.ico
│ └── logo.png
├── .env.example
├── package.json
├── vite.config.js
├── README.md
└── Dockerfile

3. Install and Run Locally

Install dependencies and start the development server:

Terminal window
npm install
npm run dev

Your Vue app will be available at http://localhost:5173. The development server provides hot module replacement (HMR) for instant updates as you code.

4. Create Your First Component

Create src/components/Header.vue:

<template>
<header class="header">
<div class="container">
<h1>{{ title }}</h1>
<p>Deployed on Klutch.sh</p>
</div>
</header>
</template>
<script setup>
defineProps({
title: {
type: String,
default: 'My Vue App'
}
})
</script>
<style scoped>
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 2rem;
text-align: center;
margin-bottom: 2rem;
}
h1 {
margin: 0;
font-size: 2.5rem;
}
p {
margin: 0.5rem 0 0;
font-size: 1.1rem;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
</style>

5. Create a Counter Component with Composition API

Create src/components/Counter.vue:

<template>
<div class="counter">
<h2>Counter Demo</h2>
<div class="counter-display">{{ count }}</div>
<div class="counter-buttons">
<button @click="increment" class="btn btn-success">
Increment
</button>
<button @click="decrement" class="btn btn-danger">
Decrement
</button>
<button @click="reset" class="btn btn-secondary">
Reset
</button>
</div>
<div v-if="history.length > 0" class="history">
<h3>History</h3>
<p>{{ history.join(', ') }}</p>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
const count = ref(0)
const history = ref([])
const increment = () => {
count.value += 1
history.value.push(count.value)
}
const decrement = () => {
count.value -= 1
history.value.push(count.value)
}
const reset = () => {
count.value = 0
history.value = []
}
const isPositive = computed(() => count.value > 0)
</script>
<style scoped>
.counter {
padding: 2rem;
border: 1px solid #ddd;
border-radius: 8px;
text-align: center;
margin-bottom: 2rem;
background: #f9f9f9;
}
.counter-display {
font-size: 3rem;
font-weight: bold;
color: #667eea;
margin: 1rem 0;
}
.counter-buttons {
display: flex;
gap: 1rem;
justify-content: center;
margin: 1.5rem 0;
flex-wrap: wrap;
}
.btn {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
transition: opacity 0.3s ease;
}
.btn:hover {
opacity: 0.8;
}
.btn-success {
background-color: #27ae60;
color: white;
}
.btn-danger {
background-color: #e74c3c;
color: white;
}
.btn-secondary {
background-color: #95a5a6;
color: white;
}
.history {
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid #ddd;
}
.history h3 {
margin-top: 0;
}
</style>

6. Create a Pinia Store

Create src/stores/auth.js:

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useAuthStore = defineStore('auth', () => {
const user = ref(null)
const token = ref(localStorage.getItem('token') || null)
const loading = ref(false)
const error = ref(null)
const isAuthenticated = computed(() => !!user.value)
const login = async (email, password) => {
loading.value = true
error.value = null
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
})
const data = await response.json()
if (response.ok) {
user.value = data.user
token.value = data.token
localStorage.setItem('token', data.token)
} else {
error.value = data.message
}
} catch (err) {
error.value = err.message
} finally {
loading.value = false
}
}
const logout = () => {
user.value = null
token.value = null
localStorage.removeItem('token')
}
return {
user,
token,
loading,
error,
isAuthenticated,
login,
logout
}
})

7. Create Composables for API

Create src/composables/useApi.js:

import { ref } from 'vue'
import { useAuthStore } from '@/stores/auth'
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000'
export function useApi(url, options = {}) {
const data = ref(null)
const loading = ref(false)
const error = ref(null)
const authStore = useAuthStore()
const fetch = async () => {
loading.value = true
error.value = null
try {
const response = await window.fetch(`${API_BASE_URL}${url}`, {
...options,
headers: {
'Content-Type': 'application/json',
'Authorization': authStore.token ? `Bearer ${authStore.token}` : '',
...options.headers
}
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
data.value = await response.json()
} catch (err) {
error.value = err.message
data.value = null
} finally {
loading.value = false
}
}
return { data, loading, error, fetch }
}

8. Create API Service

Create src/services/api.js:

import { useAuthStore } from '@/stores/auth'
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000'
function getHeaders() {
const authStore = useAuthStore()
return {
'Content-Type': 'application/json',
'Authorization': authStore.token ? `Bearer ${authStore.token}` : ''
}
}
export const api = {
get: async (endpoint) => {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
headers: getHeaders()
})
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: getHeaders(),
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: getHeaders(),
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: getHeaders()
})
if (!response.ok) throw new Error(`API error: ${response.status}`)
return response.json()
}
}

9. Create Router Configuration

Update src/router/index.js:

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: AboutView
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import('../views/DashboardView.vue'),
meta: { requiresAuth: true }
}
]
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
// Navigation guard for auth
router.beforeEach((to, from, next) => {
const authStore = useAuthStore()
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
next('/login')
} else {
next()
}
})
export default router

10. Create Home View

Create src/views/HomeView.vue:

<template>
<div class="home">
<Header title="Vue on Klutch.sh" />
<main class="container">
<section>
<h2>Welcome to Vue</h2>
<p>Vue is a progressive framework for building user interfaces.</p>
<ul class="features">
<li>📖 Easy to learn and use</li>
<li>⚡ Reactive and performant</li>
<li>🛠️ Powerful tooling ecosystem</li>
<li>🌐 Great for SPAs and PWAs</li>
</ul>
</section>
<section class="demo-section">
<h2>Interactive Demo</h2>
<Counter />
</section>
</main>
<Footer />
</div>
</template>
<script setup>
import Header from '@/components/Header.vue'
import Counter from '@/components/Counter.vue'
import Footer from '@/components/Footer.vue'
</script>
<style scoped>
.home {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1;
padding: 2rem 1rem;
max-width: 1200px;
margin: 0 auto;
width: 100%;
}
h2 {
color: #333;
}
.features {
list-style: none;
padding: 0;
}
.features li {
padding: 0.5rem 0;
font-size: 1.1rem;
}
.demo-section {
margin-top: 3rem;
}
</style>

11. Create Environment Variables

Create .env.example:

VITE_API_URL=http://localhost:3000
VITE_APP_NAME=My Vue App
VITE_ANALYTICS_ID=
VITE_ENABLE_DEBUG=false

12. Configure Build

Update vite.config.js:

import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
port: 5173,
strictPort: false
},
build: {
target: 'esnext',
minify: 'terser',
sourcemap: false,
cssCodeSplit: true
}
})

13. Build Optimization

Create a production build with optimizations:

Terminal window
npm run build

This creates an optimized, minified bundle in the dist/ directory ready for production deployment.

14. Test Production Build Locally

Serve the production build locally:

Terminal window
npm install -g http-server
http-server dist -p 3000

Visit http://localhost:3000 to test your production build.


Local Production Build Test

Before deploying, test your application in a production-like environment:

Terminal window
# Build for production
npm run build
# Serve the production build
http-server dist -p 3000 --gzip

Verify 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
  • Navigation works smoothly
  • Stores maintain state properly

Deploying with Nixpacks

Nixpacks automatically detects your Vue application and configures build and runtime environments without requiring a Dockerfile. This is the simplest deployment method for Vue apps.

Prerequisites for Nixpacks Deployment

  • Your Vue project pushed to a GitHub repository
  • Valid package.json with build and start scripts
  • No Dockerfile in the repository root (if one exists, Klutch.sh will use Docker instead)

Steps to Deploy with Nixpacks

  1. Push Your Vue App to GitHub

    Initialize and push your project to GitHub:

    Terminal window
    git init
    git add .
    git commit -m "Initial Vue app"
    git branch -M main
    git remote add origin git@github.com:YOUR_USERNAME/YOUR_REPO.git
    git push -u origin main
  2. Log In to Klutch.sh Dashboard

    Go to klutch.sh/app and sign in with your GitHub account.

  3. Create a Project

    Navigate to the Projects section and create a new project for your Vue app.

  4. Create an App

    Click “Create App” and select your GitHub repository.

  5. Select the Branch

    Choose the branch you want to deploy (typically main).

  6. Configure Traffic Type

    Select HTTP as the traffic type for Vue (a web application serving HTML/CSS/JS).

  7. Set the Internal Port

    Set the internal port to 3000 – this is the port where Nixpacks will serve your Vue app using a production HTTP server.

  8. Add Environment Variables (Optional)

    Add any environment variables your Vue app requires:

    VITE_API_URL=https://api.example.com
    VITE_APP_NAME=My Vue App
    VITE_ANALYTICS_ID=your-analytics-id
    NODE_ENV=production

    If 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)
  9. Configure Compute Resources

    Select your region, compute size, and number of instances based on expected traffic.

  10. Deploy

    Click “Create” to start the deployment. Nixpacks will automatically build and deploy your Vue 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 Vue

Create a Dockerfile in the root of your Vue 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 Vue SPA
RUN 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=3000
EXPOSE 3000
CMD ["npx", "http-server", "dist", "-p", "3000", "--gzip"]

Dockerfile Notes

  • Build stage: Installs dependencies and builds your Vue app.
  • Production stage: Uses Nginx (recommended for SPAs) or http-server to serve your static files.
  • Port: The PORT environment variable is set to 3000 for http-server or 80 for 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.html for proper client-side routing.
  • Caching headers: Nginx configuration includes long-term caching for static assets.

Steps to Deploy with Docker

  1. Create a Dockerfile

    Add the Dockerfile (shown above) to the root of your Vue repository.

  2. Test Locally (Optional)

    Build and test the Docker image locally:

    Terminal window
    docker build -t vue-app:latest .
    docker run -p 3000:80 vue-app:latest

    Visit http://localhost:3000 to verify.

  3. Push to GitHub

    Commit and push the Dockerfile and your code:

    Terminal window
    git add Dockerfile
    git commit -m "Add Dockerfile for production deployment"
    git push origin main
  4. Create an App in Klutch.sh

    Go to klutch.sh/app, navigate to “Create App”, and select your repository.

  5. Configure the App
    • Traffic Type: Select HTTP
    • Internal Port: Set to 80 (Nginx) or 3000 (http-server)
    • Environment Variables: Add any required runtime variables
  6. 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.com
VITE_APP_NAME=My Vue App
VITE_ANALYTICS_ID=your-analytics-id
NODE_ENV=production

Accessing Environment Variables

Access environment variables in your Vue app through import.meta.env:

// In your components or services
const 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 in component
<template>
<h1>{{ appName }}</h1>
<p>Environment: {{ isProd ? 'production' : 'development' }}</p>
</template>

Building with Custom Environment Variables

Ensure environment variables are prefixed with VITE_ to be available in the browser:

Terminal window
VITE_API_URL=https://api.example.com npm run build

Persistent Storage

If your Vue 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

  1. In the Klutch.sh dashboard, go to your app’s Volumes section.
  2. Click Add Volume.
  3. Set the mount path (e.g., /data, /uploads, /cache).
  4. Set the size (e.g., 1 GiB, 5 GiB).
  5. Save and redeploy your app.

Example: Using localStorage with Server Sync

// Sync browser localStorage with server
export function 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))
}
}

Usage in component:

<script setup>
import { onMounted, onBeforeUnmount } from 'vue'
onMounted(() => {
window.addEventListener('beforeunload', syncDataToServer)
})
onBeforeUnmount(() => {
window.removeEventListener('beforeunload', syncDataToServer)
})
</script>

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 storage
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content
|| localStorage.getItem('csrf-token')
// Add to API requests
export 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 email
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
return emailRegex.test(email)
}
// Sanitize HTML input
function sanitizeInput(input) {
const div = document.createElement('div')
div.textContent = input
return div.innerHTML
}

Usage in component:

<script setup>
import { ref } from 'vue'
const email = ref('')
const error = ref('')
function handleSubmit() {
if (!validateEmail(email.value)) {
error.value = 'Invalid email address'
return
}
// Submit form
}
</script>
<template>
<form @submit.prevent="handleSubmit">
<input v-model="email" type="email" required />
<p v-if="error" class="error">{{ error }}</p>
<button type="submit">Submit</button>
</form>
</template>
<style scoped>
.error {
color: red;
}
</style>

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 secrets
const apiKey = 'sk_live_abc123...'
// ✓ CORRECT - Use environment variables
const apiKey = import.meta.env.VITE_API_KEY
// Never expose secrets in client-side code
// For sensitive operations, call a backend API instead

7. Dependency Security

Keep dependencies updated and audit for vulnerabilities:

Terminal window
npm outdated
npm audit
npm audit fix
npm update

Monitoring and Logging

Performance Monitoring

Monitor Vue app performance using Web Vitals:

import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals'
function sendToAnalytics(metric) {
if (import.meta.env.PROD) {
fetch('/api/metrics', {
method: 'POST',
body: JSON.stringify({
name: metric.name,
value: metric.value
})
})
}
}
getCLS(sendToAnalytics)
getFID(sendToAnalytics)
getFCP(sendToAnalytics)
getLCP(sendToAnalytics)
getTTFB(sendToAnalytics)

Error Tracking

Implement global error handling:

export function setupErrorTracking(app) {
app.config.errorHandler = (err, instance, info) => {
console.error('Vue error:', err)
if (import.meta.env.PROD) {
api.post('/api/errors', {
message: err.message,
stack: err.stack,
component: info,
url: window.location.href,
timestamp: new Date().toISOString()
})
}
}
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()
})
}
})
}

Analytics Integration

Add analytics tracking to monitor user behavior:

export function setupAnalytics(router) {
router.afterEach((to, from) => {
// Google Analytics
window.gtag?.('config', 'GA_ID', {
page_path: to.path,
page_title: document.title
})
})
}

Custom Domains

To use a custom domain with your Klutch.sh-deployed Vue 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.sh

3. Update Your Vue App

Update API endpoints if needed:

// API configuration
export 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:

Terminal window
nslookup app.example.com
# or
dig app.example.com CNAME

Once propagated, your Vue app will be accessible at your custom domain with automatic HTTPS.


Troubleshooting

Issue 1: Build Fails with “Module not found”

Error: Cannot find module 'vue' or similar

Solutions:

  • Run npm install to ensure all dependencies are installed
  • Check that package.json includes vue and vue-router (if using router)
  • Delete node_modules and package-lock.json, then run npm install again
  • 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 in router/index.js
  • 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 .env file: 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/users instead of full URL

Issue 5: Performance Issues

Error: Slow initial load or janky animations

Solutions:

  • Check bundle size with Vite analysis tools
  • Enable code splitting for routes using lazy loading:
    {
    path: '/dashboard',
    component: () => import('../views/DashboardView.vue')
    }
  • Optimize images and assets
  • Use Vue DevTools Profiler to identify slow components
  • Consider memoization for expensive computations:
    const expensiveValue = computed(() => {
    // expensive computation
    })

Issue 6: Blank Page on Production

Error: App shows blank page or white screen

Solutions:

  • Check browser console for JavaScript errors
  • Verify index.html is being served correctly
  • Check that Nginx/http-server is configured correctly
  • Ensure build completed successfully: check for /dist folder
  • Test production build locally before deploying
  • Clear browser cache (Ctrl+Shift+Delete)

Issue 7: Store Values Not Updating

Error: Pinia store values don’t update in components

Solutions:

  • Ensure you’re using stores correctly in components via useStore()
  • Check that store modifications trigger reactivity (avoid mutating objects directly)
  • Use proper assignment or store methods to update values
  • Verify stores are imported correctly in components

Best Practices

1. Component Organization

Organize components by feature or page:

src/components/
├── common/
│ ├── Header.vue
│ ├── Footer.vue
│ └── Navigation.vue
├── dashboard/
│ ├── DashboardLayout.vue
│ ├── StatsCard.vue
│ └── Chart.vue
└── auth/
├── LoginForm.vue
└── RegisterForm.vue

2. Use Composition API Effectively

Leverage Vue 3’s composition API for reusable logic:

composables/useCounter.js
import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const increment = () => count.value++
const decrement = () => count.value--
const reset = () => count.value = initialValue
return { count, increment, decrement, reset }
}

Usage in component:

<script setup>
import { useCounter } from '@/composables/useCounter'
const { count, increment, decrement } = useCounter()
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</div>
</template>

3. Use Pinia for Global State

Extract component logic into Pinia stores:

stores/counter.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})

4. Lazy Load Routes

Split code by route for faster initial loads:

const routes = [
{
path: '/',
component: () => import('../views/HomeView.vue')
},
{
path: '/dashboard',
component: () => import('../views/DashboardView.vue')
}
]

5. Handle Loading and Error States

Always provide feedback during data loading:

<script setup>
import { useApi } from '@/composables/useApi'
const { data, loading, error, fetch } = useApi('/api/users')
</script>
<template>
<div v-if="loading">Loading...</div>
<div v-else-if="error">Error: {{ error }}</div>
<ul v-else>
<li v-for="user in data" :key="user.id">{{ user.name }}</li>
</ul>
</template>

6. Use Semantic HTML

Write accessible HTML for better SEO and UX:

<!-- ✓ Good - semantic HTML -->
<article>
<h2>{{ title }}</h2>
<p>{{ content }}</p>
</article>
<!-- ✗ Avoid - non-semantic divs -->
<div>
<div>{{ title }}</div>
<div>{{ content }}</div>
</div>

7. Scope Styles Properly

Use scoped styles to prevent CSS conflicts:

<template>
<div class="card">
<h3>{{ title }}</h3>
<p>{{ content }}</p>
</div>
</template>
<style scoped>
.card {
padding: 1rem;
border: 1px solid #ddd;
}
h3 {
margin-top: 0;
}
</style>

8. Test Your Components

Write unit tests for critical components:

import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import Counter from '@/components/Counter.vue'
describe('Counter', () => {
it('increments count', async () => {
const wrapper = mount(Counter)
await wrapper.find('button').trigger('click')
expect(wrapper.vm.count).toBe(1)
})
})

9. Document Your Components

Add comments for clarity:

<!--
Card component for displaying information
@slot default - The card content
@prop title - The card title
@prop icon - Optional icon name
-->
<template>
<div class="card">
<h3>{{ title }}</h3>
<slot />
</div>
</template>

10. Keep Dependencies Updated

Regularly update Vue and dependencies:

Terminal window
npm outdated
npm update
npm audit fix

Verifying Your Deployment

After deployment completes:

  1. Check the App URL: Visit your app at https://example-app.klutch.sh or your custom domain.
  2. Test Interactivity: Click buttons, navigate routes, and submit forms.
  3. Check Console: Open F12 and verify no errors appear.
  4. Test API Integration: Verify API calls work and return expected data.
  5. Check Performance: Use Google PageSpeed Insights to verify performance metrics.
  6. Test Responsiveness: Verify mobile, tablet, and desktop layouts work.
  7. 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


Deploying a Vue 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 Vue project with modern tools, build performant components, manage state effectively with composition API and Pinia, integrate with external APIs, optimize builds, configure environment variables, implement security best practices, set up monitoring, and troubleshoot common issues. Your Vue 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 Vue documentation or contact Klutch.sh support.