Deploy SvelteKit
This guide will help you deploy a SvelteKit application to Deployxa.
Overview
SvelteKit is a framework for building web applications with Svelte, providing server-side rendering, file-based routing, and API routes. Deployxa provides optimized deployments for SvelteKit with automatic configuration.
Features:
- Automatic framework detection
- Server-side rendering (SSR)
- Static site generation (SSG)
- API routes support
- Automatic HTTPS
- Global CDN
Prerequisites
- A SvelteKit application
- A GitHub repository with your code
- A Deployxa account
Quick Start
1. Create Your SvelteKit App
If you don't have a SvelteKit app yet:
npm create svelte@latest my-sveltekit-app
cd my-sveltekit-app
npm install
2. Push to GitHub
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/my-sveltekit-app.git
git push -u origin main
3. Deploy to Deployxa
- Go to Deployxa Dashboard
- Click "New Project"
- Select your GitHub repository
- Deployxa will automatically detect SvelteKit
- Click "Deploy"
Your app will be live in under 60 seconds!
Configuration
Detected Settings
Deployxa automatically detects these settings:
| Setting | Value |
|---|---|
| Framework | SvelteKit |
| Build Command | npm run build |
| Output Directory | .svelte-kit |
| Start Command | node build/index.js |
| Port | 3000 |
Custom Configuration
If you need to customize settings:
- Go to Project → Settings → Build
- Modify settings as needed
- Save changes
Example Custom Settings:
{
"buildCommand": "npm run build",
"outputDirectory": ".svelte-kit",
"startCommand": "node build/index.js"
}
Environment Variables
Adding Environment Variables
- Go to Project → Environment
- Click "Add Variable"
- Enter key and value
- Click "Save"
Common SvelteKit Environment Variables:
PUBLIC_API_URL=https://api.example.com
API_SECRET=your-api-secret
DATABASE_URL=postgresql://user:pass@host:5432/db
Note: Variables prefixed with PUBLIC_ are exposed to the client.
Using Environment Variables
In your SvelteKit app:
// Server-side only
import { env } from '$env/dynamic/private';
const apiSecret = env.API_SECRET;
// Available on both server and client
import { env } from '$env/dynamic/public';
const apiUrl = env.PUBLIC_API_URL;
Build Process
What Happens During Build
- Install Dependencies:
npm installornpm ci - Run Build:
npm run build - Generate Server Bundle: Build server-side code
- Generate Client Bundle: Build client-side code
- Create Output: Generate
builddirectory - Deploy: Deploy to edge network
Build Output
SvelteKit generates:
build/- Build output directorybuild/index.js- Server entry pointbuild/client/- Client-side assetsbuild/server/- Server-side code
Rendering Modes
Server-Side Rendering (SSR)
Default mode for dynamic content:
// svelte.config.js
export default {
kit: {
adapter: adapter()
}
};
Benefits:
- SEO friendly
- Fast initial load
- Dynamic content
Static Site Generation (SSG)
For mostly static content:
// svelte.config.js
import adapter from '@sveltejs/adapter-static';
export default {
kit: {
adapter: adapter({
pages: 'build',
assets: 'build',
fallback: null
})
}
};
Benefits:
- Fast load times
- CDN caching
- Low resource usage
Prerendering
Prerender specific pages:
// src/routes/+page.js
export const prerender = true;
API Routes
Creating API Routes
Create files in src/routes/api/:
// src/routes/api/hello/+server.js
import { json } from '@sveltejs/kit';
export async function GET() {
return json({
message: 'Hello from SvelteKit API!'
});
}
Access: https://your-app.deployxa.app/api/hello
With Database
// src/routes/api/users/+server.js
import { json } from '@sveltejs/kit';
import { prisma } from '$lib/prisma';
export async function GET() {
const users = await prisma.user.findMany();
return json(users);
}
POST Requests
// src/routes/api/users/+server.js
import { json } from '@sveltejs/kit';
export async function POST({ request }) {
const body = await request.json();
// Process body
return json({ success: true });
}
Custom Domains
Adding a Custom Domain
- Go to Project → Domains
- Click "Add Domain"
- Enter your domain (e.g.,
example.com) - Configure DNS records
- Wait for verification
DNS Configuration
For Apex Domain (example.com):
Type: A
Name: @
Value: 76.76.21.21
For Subdomain (www.example.com):
Type: CNAME
Name: www
Value: cname.deployxa.com
Performance Optimization
Enable Compression
SvelteKit automatically enables compression.
Enable Caching
Configure caching in +page.js:
// src/routes/+page.js
export const load = async ({ fetch }) => {
const response = await fetch('/api/data', {
cache: 'public, max-age=3600'
});
return { data: await response.json() };
};
Optimize Images
Use @sveltejs/enhanced-img:
npm install -D @sveltejs/enhanced-img
<script>
import enhanced from '$lib/image.jpg?enhanced';
</script>
<img src={enhanced.src} alt="Enhanced image" />
Code Splitting
SvelteKit automatically code-splits by default.
Monitoring
Viewing Logs
- Go to Project → Logs
- Select log type:
- Build Logs: Deployment process
- Runtime Logs: Application output
- Error Logs: Application errors
Monitoring Metrics
- Go to Project → Analytics
- View metrics:
- Request count
- Response times
- Error rates
- Bandwidth usage
- CPU/RAM usage
Health Checks
Deployxa automatically monitors your application:
- HTTP health checks every 30 seconds
- Automatic restart on failure
- Alerts on consecutive failures
Troubleshooting
Build Failed: Module Not Found
Problem: Cannot find package 'package-name'
Solution:
- Check
package.jsonhas the dependency - Run
npm install package-namelocally - Commit and push changes
- Redeploy
Runtime Error: Port Already in Use
Problem: Error: listen EADDRINUSE: address already in use :::3000
Solution:
- Deployxa automatically handles port configuration
- Ensure your code uses
process.env.PORTor defaults to 3000
Pages Not Loading
Problem: Pages return 404 or blank
Solution:
- Check build logs for errors
- Verify file structure
- Ensure
svelte.config.jsis correct - Check runtime logs for errors
API Routes Not Working
Problem: API routes return 404
Solution:
- Check files are in
src/routes/api/directory - Verify file naming convention (
+server.js) - Check runtime logs for errors
- Ensure proper HTTP method handling
Slow Build Times
Problem: Build takes too long
Solution:
- Use
npm ciinstead ofnpm install - Enable dependency caching
- Reduce build steps
- Consider upgrading plan
Best Practices
Project Structure
my-sveltekit-app/
├── src/
│ ├── routes/
│ │ ├── +page.svelte
│ │ ├── +page.js
│ │ └── api/
│ │ └── hello/
│ │ └── +server.js
│ ├── lib/
│ │ └── index.js
│ └── app.html
├── static/
│ └── favicon.png
├── svelte.config.js
├── package.json
└── README.md
Environment Variables
- Use
.envfor local development - Never commit
.envfiles - Use
PUBLIC_prefix for client-side variables - Rotate secrets regularly
Performance
- Use prerendering when possible
- Enable image optimization
- Use code splitting
- Minimize bundle size
- Enable compression
Security
- Never expose secrets in client code
- Use HTTPS only
- Validate all inputs
- Use CSRF protection
- Keep dependencies updated
Advanced Configuration
Custom SvelteKit Config
// svelte.config.js
import adapter from '@sveltejs/adapter-node';
export default {
kit: {
adapter: adapter({
out: 'build',
precompress: false,
envPrefix: ''
}),
alias: {
$components: 'src/lib/components',
$utils: 'src/lib/utils'
}
}
};
Custom Server
For advanced use cases, you can customize the server:
// src/hooks.server.js
export async function handle({ event, resolve }) {
// Custom request handling
const response = await resolve(event);
return response;
}
Examples
Basic SvelteKit App
<!-- src/routes/+page.svelte -->
<script>
let count = 0;
</script>
<h1>Welcome to SvelteKit on Deployxa!</h1>
<button on:click={() => count++}>
Count: {count}
</button>
With Data Fetching
<!-- src/routes/+page.svelte -->
<script>
export let data;
</script>
<h1>{data.title}</h1>
// src/routes/+page.js
export async function load({ fetch }) {
const response = await fetch('/api/data');
return {
data: await response.json()
};
}
API Route
// src/routes/api/users/+server.js
import { json } from '@sveltejs/kit';
export async function GET() {
return json([
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]);
}
Related Topics
Resources
Need Help? Contact support@deployxa.com or join our community Discord.