Skip to main content

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

  1. Go to Deployxa Dashboard
  2. Click "New Project"
  3. Select your GitHub repository
  4. Deployxa will automatically detect SvelteKit
  5. Click "Deploy"

Your app will be live in under 60 seconds!

Configuration

Detected Settings

Deployxa automatically detects these settings:

SettingValue
FrameworkSvelteKit
Build Commandnpm run build
Output Directory.svelte-kit
Start Commandnode build/index.js
Port3000

Custom Configuration

If you need to customize settings:

  1. Go to ProjectSettingsBuild
  2. Modify settings as needed
  3. Save changes

Example Custom Settings:

{
"buildCommand": "npm run build",
"outputDirectory": ".svelte-kit",
"startCommand": "node build/index.js"
}

Environment Variables

Adding Environment Variables

  1. Go to ProjectEnvironment
  2. Click "Add Variable"
  3. Enter key and value
  4. 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

  1. Install Dependencies: npm install or npm ci
  2. Run Build: npm run build
  3. Generate Server Bundle: Build server-side code
  4. Generate Client Bundle: Build client-side code
  5. Create Output: Generate build directory
  6. Deploy: Deploy to edge network

Build Output

SvelteKit generates:

  • build/ - Build output directory
  • build/index.js - Server entry point
  • build/client/ - Client-side assets
  • build/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

  1. Go to ProjectDomains
  2. Click "Add Domain"
  3. Enter your domain (e.g., example.com)
  4. Configure DNS records
  5. 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

  1. Go to ProjectLogs
  2. Select log type:
    • Build Logs: Deployment process
    • Runtime Logs: Application output
    • Error Logs: Application errors

Monitoring Metrics

  1. Go to ProjectAnalytics
  2. 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:

  1. Check package.json has the dependency
  2. Run npm install package-name locally
  3. Commit and push changes
  4. 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.PORT or defaults to 3000

Pages Not Loading

Problem: Pages return 404 or blank

Solution:

  1. Check build logs for errors
  2. Verify file structure
  3. Ensure svelte.config.js is correct
  4. Check runtime logs for errors

API Routes Not Working

Problem: API routes return 404

Solution:

  1. Check files are in src/routes/api/ directory
  2. Verify file naming convention (+server.js)
  3. Check runtime logs for errors
  4. Ensure proper HTTP method handling

Slow Build Times

Problem: Build takes too long

Solution:

  1. Use npm ci instead of npm install
  2. Enable dependency caching
  3. Reduce build steps
  4. 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 .env for local development
  • Never commit .env files
  • 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' }
]);
}

Resources


Need Help? Contact support@deployxa.com or join our community Discord.