sveltekit In Production

I've been experimenting with sveltekit for a few small projects and it's been resonating with me. The naming of files is a little funky but the separation it provides is very clear and obvious.

After changing my link.david-reid.com site over to using shlink I found I needed something quick and simple to create the index page. The shortening works really well but I like having the list on the root of the site, so a small renderer was required.

I could have written it in plain javascript or anything else, but I thought it would be a useful way of gaining more experience with sveltekit.

Having created the skeleton app, it took only a short while to add the server side code to pull the list of links and then display them. I was surprised how simple it was. Add some quick CSS and some query handling for pages and it was done. This is as far as I had come with any of my other experiments, so now it was time to move beyond

$ npm run dev

and figure out how to deploy this into a live environment.

The first step was to build for production. So surely this

$ npm run build

which appeared to work, but I was then left trying to figure out what it had done. Looking at the files it didn't look as I expected. Hmm.

It turns out I needed to install and use the node adapter.

$ npm i @sveltejs/adapter-node --save-dev

Then the svelte.config.js file needed to be edited to change the adapter import to

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

Finally to make things clearer I also added an output directory to the process.

kit: {
		adapter: adapter({out: "build"})
	}

Having done this, it was time for another

$ npm run build

This time the files I was expecting were in the build directory. Progress.

Next, on the server I copied across the entire build directory, but following some online guidance I also copied across the package.json file from the main directory. Why this wasn't copied for me into the build directory I'm not sure, but it's omission was quickly apparent.

$ cd build
$ npm i
$ node ./index.js

I did have some issues getting the node modules installed, though that was likely a peculiarity of my environment.

I also changed the port in the index.js file to reflect where I wanted to access it from the apache2 proxy I had setup. As it shares the same domain as shlink I used the ProxyPassMatch configuration to narrow the url's it was used for. After a bit of trial and error it appears to work well enough.

The final step was to add the systemd service file and enable/start it.

Overall it was easier than I expected but still a few learning points for me. Next time I may try one of the package runners which people seem to like.