KINTO Tech Blog
Development

Deploying SvelteKit to AWS - Irregular Svelte series 06

Cover Image for Deploying SvelteKit to AWS - Irregular Svelte series 06

Hello (or good evening), this is the part 6 of our irregular Svelte series. To read previous articles, you can click on the links below:

  1. Insights from using SvelteKit + Svelte for a year
  2. Comparison of Svelte and other JS frameworks - Irregular Svelte series-01
  3. Svelte unit test - Irregular Svelte series 02
  4. Using Storybook with Svelte - Irregular Svelte Series 03
  5. Exploring Svelte in Astro - Irregular Svelte series 04
  6. SvelteTips - Irregular Svelte series 05

In this article, I will be writing about SvelteKit SSR deployments.

You can get the module here.

@sveltejs/adapter-node

Deployment of SSR requires an adapter. This time, I will use the Node adapter.
https://www.npmjs.com/package/@sveltejs/adapter-node

This adapter is also listed on the official GitHub.
https://github.com/sveltejs/kit

Express

This is a web framework for Node.js. Others include Fastify, but you are free to use any of them.
https://www.npmjs.com/package/express

Environment Settings

First, configure the settings in Svelte. SvelteKit is SSR by default, so there is no need to set anything special there. On the other hand, you need to use an adapter to build when deploying. As described on the official site, from the Svelte project, install with

yarn add -D @sveltejs/adapter-node

and add the following code to svelte.config.js.

svelte.config.js
import adapter from '@sveltejs/adapter-node';

const config = {
	kit: {
		adapter: adapter()
	}
};

export default config;

After building your project with yarn build, the resulting files will be placed in the default output location, /build, and the files, index.js and handler.js will be created. If you want to use the server as is with the built file, you can execute node build to run build/index.js to start the server and check it works. (The default is build because xxxx in node xxxx is the output location for the built files.)

Next, put the Express configuration file in the root directory. (Please install express in advance.)

server.js
import { handler } from './build/handler.js';
import express from 'express';

const app = express();

// For example, create a health check pass for AWS that is not related to the SvelteKit app created
app.get('/health', (_, res) => {
  var param = { value: 'success' };
	res.header('Content-Type', 'application/json; charset=utf-8');
	res.send(param);
});

// Svelte created with build is handled here
app.use(handler);

app.listen(3000, () => {
	console.log('listening on port 3000');
});

After completing the above settings, you can start the Express server with node server.js and check the SvelteKit app at http://localhost:3000.

Deploy the App to AWS

From here on, we will deploy it to AWS. In AWS, deployments can be configured in various ways depending on the requirements. In this article, I will show you how to access the app from the Internet using only EC2. For security and performance reasons, please consider combinations such as CloudFront, ALB, and VPC in practice.

As the AWS services incur charges, it is advisable to monitor costs and stop the unused service.

EC2

This is a cloud server service to host the SvelteKit app I have created.
https://aws.amazon.com/jp/ec2/

Create an EC2 Instance

First, I would like to start from setting up EC2. To create an EC2 instance, go to the EC2 Dashboard and click "Launch Instance" in the upper right corner.

EC2 start instance

Then you will be redirected to the screen shown above. Configure the following items and click "Launch Instance."

  1. Name: Choose a name to identify your instance easily.
  2. OS images: You can adjust according to your preferences, but for this article, I will be using Amazon Linux, with subsequent commands based on the same.
  3. Instant type: t2.micro (otherwise, charges apply)
  4. Key pair: In this article, I will access EC2 with an SSH client, so set it up.
  5. Network settings: I will enable HTTP access to allow connection via an SSH client and for basic web accessibility checks.

Connect to the EC2 Instance

After creating an EC2, you will be returned to the list screen, where you should see the newly created instance. Next, proceed to connect to the instance and configure any remaining settings. Choose Instances from the list screen and click the "Connect" button. Then, you can choose from four connection methods, but this time, I will use SSH.

Instance connect

I assume that you have already created and downloaded a key pair on the instance launch screen earlier. Use that key as instructed on the screen to connect. Once the connection is made successfully, install various things.

Setting Up Node.js

I am going to install Node.js first. You can install different Node.js versions using the Node Version Manager (NVM), which offers convenient switching between them.

https://github.com/nvm-sh/nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

After installation, you will get a message from the terminal. You need to pass the nvm command so that it can be executed. Copy the following code, paste it into the command line, and execute it.

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

// Check if the nvm command works
nvm --version
-> 0.34.0

And install Node.js with nvm

// Install Node.js 18
nvm install 18

// Check the installed node and npm version
node -v
-> 18.16.1
npm -v
-> 9.5.1

// Install yarn (skip this if you want to use npm)
npm install -g yarn
yarn -v
-> 1.22.19

The Node.js setup is now complete.

SvelteKit App Placement

Next, I would like to put the app I created in an instance. There is also a way to move it from your local to EC2, but this time, I will clone it from the repository on GitHub.

First, install GitHub CLI so that it can be cloned. Installation instructions for Linux can also be found in official documentation.

// commands listed in the official documentation (Be sure to check the official documentation as it may change.)
type -p yum-config-manager >/dev/null || sudo yum install yum-utils
sudo yum-config-manager --add-repo https://cli.github.com/packages/rpm/gh-cli.repo
sudo yum install gh

// Version check
gh --version
-> 2.31.0

Next, log in with your account and clone the repository.

// Login to GitHub
gh auth login

// Put the url of the repository you want to clone
gh repo clone https://github.com/xxxxxx/yyyyyyy

Now the app has been successfully cloned to the instance.

Setting Up Nginx

The next step is to install the Nginx server and modify the config file.

// Install
sudo yum install nginx

// Go to the nginx folder
cd /etc/nginx

// Open the nginx config file with vim
sudo vim nginx.conf

In the config file, there is a section called server. Set the proxy path as follows. This syntax instructs nginx to access the SvelteKit server launched in EC2 when accessing /.

server {
	location / {
		proxy_pass http://localhost:3000;
	}
}

Launch the Node Server and Access it from the Web

Finally, build and start the node server, just as you did for the local check.

yarn install
yarn build
node server.js

Then, try accessing it from the DNS name provided by the EC2 instance you created. (Information can be found on the EC2 listing page.)

Public DNS

You should now see something like this!

SvelteKit App

However, if you stop the connection with the EC2 instance, the Node server will also be stopped. So, we use a library called pm2 to persist the Node server.

https://pm2.io/docs/runtime/guide/installation/

yarn global add pm2

pm2 -v
-> 5.3.0

pm2 start server.js

// Check the status of the node server currently running with pm2 and the server id you want to stop.
pm2 status

// Stop the node server currently running with pm2
pm2 stop [id]

Now, even if you disconnect from EC2, you can still browse from the web!

This is all on how to deploy a SvelteKit SSR app to AWS.

Facebook

関連記事 | Related Posts

We are hiring!

【プラットフォームエンジニア】プラットフォームG/東京・大阪

プラットフォームグループについてAWS を中心とするインフラ上で稼働するアプリケーション運用改善のサポートを担当しています。

【クラウドエンジニア】Cloud Infrastructure G/東京・大阪

KINTO Tech BlogWantedlyストーリーCloud InfrastructureグループについてAWSを主としたクラウドインフラの設計、構築、運用を主に担当しています。