Host SvelteKit apps with SSR-support via ploi.io (on Hetzner Cloud)
Tags: sveltekit, svelte, devops, cloud
Published: 2022-12-16 20:27:20

[SvelteKit 1.0](https://svelte.dev/blog/announcing-sveltekit-1.0) was officially released a few hours ago 🥳. Time to dive  into NodeJS and SvelteKit hosting. One key advantage of SvelteKit is that you can generate static sites as well as take advantage of [Server Side Rendering (SSR)](https://dev.to/mandrasch/rich-harris-explains-why-sveltekit-pushes-for-server-side-rendering-and-against-spa-5flj). The best thing: You can mix these approaches. 

> Mix and match prerendered pages for maximum performance with dynamic server-side rendering for maximum flexibility.

In order to use the SSR features, you need to host your app as NodeJS application. 

One option for this is to use the awesome server management service ploi.

## ploi.io

[Ploi.io](https://ploi.io/) is like a nice graphical user interface for managing and configuring virtual private servers (VPS). Ploi does not host your site, it's just a middleware service connecting to your servers. 

It basically offers three key features:

1. Create and configure (virtual) servers
2. Connect git repositories to these servers
3. Deploy applications via deploy scripts

_🇪🇺 An additional advantage is that ploi enables you to deploy NodeJS apps to various server providers like Hetzner Cloud. Hetzner offers servers which are located completely in the European Union (which is good for GDPR-compliance if you or your customers are located in the EU). I blogged about this [here](https://dev.to/mandrasch/how-to-host-sveltekit-ssr-apps-gdpr-compliant-15bh) briefly._

## Prerequisites

Steps I won't cover in this tutorial:

- Sign up for customer account on [ploi.io](https://ploi.io/)
- Sign up for a customer account on [Hetzner Cloud](https://www.hetzner.com/cloud)  
- Install a new server on Hetzner Cloud via ploi.io ([Guide: Server installation](https://ploi.io/server-installation)). I selected the CX11 type.
- Add an external domain to your server ([Guide: How do I connect my domain](https://ploi.io/documentation/domains/how-do-i-connect-my-domain-to-my-server)). You can also use [test domains](https://twitter.com/ploi_deploy/status/1281841306206187521).

## Tutorial: Deploy and host SvelteKit

### Create a new site on our server

First we need to create a new site on our server:

![Screenshot ploi site dashboard, button create site is highlighted](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bx09ruhzmsj838el53vb.png)

Expand the advanced settings and use the following:

![Screenshot ploi site dashboard, form for site generation with web directory to slash, project directory to slash, project type nodejs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fkih7ac5wquar8omq942.png)

_(Set the project directory to `/`, otherwise you won't be able to request an SSL cert in the next steps)_

### Install project from a git repository

Afterwards we can install our project from a git repository:

![Screenshot ploi site dashboard with install git button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4kuj5e882piqhxit956f.png)

I added my GitHub account and used my demo repo [sveltekit-company-demo](https://github.com/mandrasch/sveltekit-company-demo):

![Screenshot github added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fz5pg85kxwbeh4o1vyj3.png)

After adding a repository you can edit the deploy script of your new site:

![Screenshot deploy script](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfzvwf056nrpttbqllxz.png)

Replace it with the following, we will need to add `npm run build`:

```
cd /home/ploi/sveltekit-company-demo.mandrasch.dev
git pull origin main
# install
npm install
npm run build

# Server restarting is handled by plois NodeJS settings
echo "🚀 Application deployed!"
```

### SSL certificate

We will also need a SSL certificate. Thanks to the Lets's Encrypt initiative this is easily done nowadays:

![Screenshot ploi request ssl certificate successful](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfv6icar4p0jsdegtdov.png)

### NodeJS settings (pm2)

Now we need to make adjustments to the NodeJS settings. ploi will use [pm2](https://pm2.keymetrics.io/) by default to host our SvelteKit app, Supervisor is also possible.

Change the NodeJS settings to the following: 

![Screenshot ploi node js settings with PORT=3001 node build/index.js and port 3001 selected](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/op73m2mlx80c9arkaryf.png)

Important: If you create your first site, it will run on port 3000. SvelteKits [adapter-node](https://github.com/sveltejs/kit/tree/master/packages/adapter-node) assumes port 3000 by default. But if you add another site on a server, ploi will use a different port like 3001, 3002, etc. for each new project.

Therefore we need to make sure to set the env variable for the specific port correctly:

`PORT=3001 node build/index.js`

Thanks very much to [aarondiel](https://stackoverflow.com/a/71228351)!

### Switch to adapter-node

In order to run our SvelteKit Web App with NodeJS, we also need to apply the following changes to our projects source code. 

We need to install [adapter-node](https://github.com/sveltejs/kit/tree/master/packages/adapter-node): 

`npm i -D @sveltejs/adapter-node` 

And we need to replace

`import adapter from '@sveltejs/adapter-auto';`

 with 

`import adapter from '@sveltejs/adapter-node';` 

in `svelte.config.js`:

```
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/kit/vite';

/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		adapter: adapter()
	},
	preprocess: vitePreprocess()
};

export default config;
```

See SvelteKits official docs for all information: 

[Adapters > Supported Environments > NodeJS](https://kit.svelte.dev/docs/adapters#supported-environments-node-js)

Commit and push these changes.

### Deploy (to the build/-directory)

It is time to deploy our app. Let's hit the "Deploy now" button! 

![Screenshot deploy now button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7ov8gs7uxh2l0lhedes.png)

You can check the status in the deployments section below: 

![Screenshot deployments section](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nl7t91j17lf1x01j2mw1.png)

### Spawn the app with pm2

Our app is now successfully prepared in the `build/` directory on the server, but we still need to start our app via the pm2 service. 

Hit "Spawn" in the NodeJS settings dashboard:

![Screenshot before spawn](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cy7p35f36vswevuu367u.png)

You should see a brief success message and the buttons beneath should change as following:

![Screenshot successful span](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wqk2cxlxidc2aqx4wjv7.png)

Congrats, your SvelteKit app is now live! 🥳🥳🥳

![Screenshot live site](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cup9pn78kndwcadjzj1m.png)

If you experience issues, see troubleshooting below.

**Have I missed something or can this be optimized? How do you host SvelteKit apps? Let me know in the comments, much appreciated!**

### Further resources

#### Troubleshooting

You can check the NodeJS error log for information if something failed. In my case I wasn't aware I need to set the PORT=3001 if I use another port than 300.

![Screenshot error logs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzcz8uvwl6o4hybfz873.png)

Investigating errors is also possible via SSH and `pm2 list` or `pm2 logs` command:

![Screenshot pm2 list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x4fbeouz7buozkgc09z7.png)
See [pm2 quickstart docs](https://pm2.keymetrics.io/docs/usage/quick-start/) for more information.

#### What is pm2? 

"PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks." ([pm2](https://www.npmjs.com/package/pm2))

{%youtube https://www.youtube.com/watch?v=ebdKIU6SDHI %}

Other similiar tools are [nodemon](https://www.npmjs.com/package/nodemon) and [supervisor](https://www.npmjs.com/package/supervisor). 

#### Reboot configuration

If this is your first time using pm2 on your Hetzner server, you need to add pm2 to the $PATH for server reboots. Follow the ploi.io-guide [How to make pm2 start on boot](https://ploi.io/documentation/server/how-to-make-pm2-start-on-boot). 

In my case I logged in to the Hetzner server `ssh ploi@x.x.x.x` via terminal / SSH. I previously added my laptops SSH key to ploi, see https://ploi.io/documentation/ssh for more information. 

![Screenshot of ssh connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmzu7qsn629y1v59est4.png)

I ran the command `pm2 startup` and pasted the suggested command (`sudo env PATH=$PATH ...`):

![Screenshot terminal command from guide one](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w0naa3nuctubo780msqv.png)

![Screenshot terminal command from guide one](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vfivrsnuumprjnqthpia.png)

_The root server password was retrieved via mail after the initial server completion (https://ploi.io/documentation/ssh/how-do-i-login-as-root-user):
![Screenshot mail ploi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1e2n1xyq4o4q7jogm3xz.png)_

#### What is SSR?

- [Rich Harris explains why SvelteKit pushes for Server Side Rendering (and against SPA / CSR)](https://dev.to/mandrasch/rich-harris-explains-why-sveltekit-pushes-for-server-side-rendering-and-against-spa-5flj)
- https://kit.svelte.dev/docs/glossary
- https://learn.svelte.dev/tutorial/ssr
- ... and more resources on YouTube, Twitter, Mastodon, etc. 

#### SvelteKit hosting and GDPR

I blogged about this topic briefly:

[How to host SvelteKit SSR apps (GDPR-compliant)?](https://dev.to/mandrasch/how-to-host-sveltekit-ssr-apps-gdpr-compliant-15bh)

In general: Big big kudos to Vercel for sponsoring the open source development of Svelte and SvelteKit in a massive way (https://vercel.com/blog/vercel-welcomes-rich-harris-creator-of-svelte)! 🙏👏