How to deploy SvelteKit in VPS, AWS EC2 or Lightsail?

March 6th 2024 549 views • 0 comments
codie 2 months ago

Deploying SvelteKit can be a tricky job, especially when you're doing it for the first time, unlike me. But, after a few deployments, you get used to with it. So, today, I am guiding you through it, and giving you exact ways to deploy and run your SvelteKit in the server.

Also, will be talking about something that I personally developed, called svelte-deploy command.

SvelteKit configuration

First of all, you need a module to be installed in your sveltekit project, @sveltejs/adapter-node;

npm install @sveltejs/adapter-node

Now, you have to configure your svelte.config.js, by adding replacing that upper module with @sveltejs/adapter-auto;

import adapter from '@sveltejs/adapter-node';
//                                ^
// replace @sveltejs/adapter-auto |

const config = {
	preprocess: [
		vitePreprocess(),
		preprocess({
			postcss: true
		})
	],
...

Now, your SvelteKit setup is almost done.

Server setup

If you have installed git in your Lightsail server then what you have to do is, clone your repo to a specific folder.

Creating a service setup

Now, we need to create a service setup /etc/systemd/system/<your_svelte_service_name>.service:

[Unit]
Description=SvelteApp
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/home/ubuntu/svelte-apps/<path-to-your-app>
ExecStart=/home/ubuntu/.nvm/versions/node/v19.8.0/bin/node /home/ubuntu/svelte-apps/<path-to-your-app>/build/index.js
Environment=PORT=3099 ORIGIN=https://yoursite.com
[Install]
WantedBy=multi-user.target

Make sure you have installed NodeJs, suggested to installed it using nvm. You can see learn about installing nvm here.

And to checkout the path of your current running node, use whereis node, and paste your preferred node to ExecStart=path_to_node path_to_index.js

Nginx Setup

upstream sveltekit-frontend {
    server localhost:3099;
}

server {
    listen 80;
    listen [::]:80;
    set $app_dir "/home/ubuntu/svelte-apps/<path-to-your-app>"; # not required
    server_name yoursite.com;
    location / {
            proxy_pass http://sveltekit-frontend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }
}

Now, run;

sudo nginx -t

If result is:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

It's usually good, and you're ready to go. (if not, ask below, happy to help)

Restart the services

Now, restart the nginx and the created services:

sudo systemctl enable <your_svelte_service_name>.service;
sudo systemctl start <your_svelte_service_name>.service;
sudo systemctl restart nginx.service;

Done, now your site is up and running. Lemme know if you need help.

Have a good day 😊