In today’s digital landscape, web application development has become increasingly important for businesses to stay competitive. SvelteKit, a powerful web application framework, offers a simplified approach to building efficient and high-performance web applications. In this article, we will explore how to deploy a SvelteKit web application on an Ubuntu server, providing step-by-step instructions and valuable insights to help you get started.
Prerequisites
Before diving into the deployment process, there are a few prerequisites that need to be met:
- Deploy a fresh Ubuntu server on Shape.host: Begin by setting up a clean Ubuntu server on Shape.host, a reliable cloud hosting provider known for its superior performance and excellent customer support.
- Set up a Domain A record: Once you have your server up and running, configure a Domain A record to point to your server’s IP address. This will ensure that your web application is accessible via a domain name.
- Access the server via SSH: Use SSH to securely access your Ubuntu server as a non-root user with sudo privileges. This will allow you to execute commands and make changes to the server without compromising its security.
- Update the Ubuntu server: Before proceeding, it’s vital to update your Ubuntu server to ensure that you have the latest security patches and software updates. Execute the following command to update your server:
sudo apt update && sudo apt upgrade -y
Install Node.js Using NVM
Next, we need to install Node.js, a JavaScript runtime environment, which is a prerequisite for running SvelteKit. Here’s how you can install Node.js using NVM (Node Version Manager):
- Download the latest NVM installer script: Use the following command to download the NVM installer script:
wget -qO https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
- Load the NVM script: Run the following command to load the NVM script into your current shell session:
source ~/.bashrc
- Install the latest Node.js version: Now, it’s time to install the latest version of Node.js using NVM. Execute the following command:
nvm install node
- Verify the installed Node.js version: To ensure that Node.js is installed correctly, run the following command to check the version:
node -v
If everything is set up correctly, you should see the installed version of Node.js printed on the console.
Create the SvelteKit Project
With Node.js installed, we can now proceed to create our SvelteKit project. Follow these steps to set up a new SvelteKit project:
- Create a new SvelteKit project: Use the following command to create a new SvelteKit project named “my-app”:
npx degit sveltejs/template my-app
- Switch to the project directory: Navigate to the project directory using the following command:
cd my-app
- Install project dependencies: Execute the following command to install the project dependencies:
npm install
- Install additional project dependencies: Install the following packages to enhance the functionality of your SvelteKit project:
npm install dotenv express helmet @godaddy/terminus
These packages provide features such as loading environment variables, creating a custom server with additional security middleware, and server cleanup functions.
Set Up the SvelteKit Adapter
By default, SvelteKit uses the “adapter-auto” configuration, which automatically detects and adapts to the target environment. However, in some cases, it may fail to choose the correct environment. To specify a target environment, we will use the Node.js adapter. Follow these steps to set up the SvelteKit adapter:
- Install the Node.js adapter package: Run the following command to install the Node.js adapter package:
npm install -D @sveltejs/adapter-node
- Configure the adapter: Create a new file named “svelte.config.js” using a text editor of your choice, and add the following configurations:
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/kit/vite';
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};
export default config;
Save the file and close the text editor.
Create a Custom Server
To fully leverage the capabilities of the Node.js adapter, we will create a custom server that provides additional functionality, such as loading environment variables, enabling security improvements, and implementing graceful shutdown. Follow these steps to create a custom server:
- Create a new server file: Use a text editor to create a new file named “server.js” and add the following code:
import 'dotenv/config';
import { handler } from './build/handler.js';
import express from 'express';
import helmet from "helmet";
import http from 'http';
import { createTerminus } from '@godaddy/terminus';
const app = express();
app.use(helmet({
contentSecurityPolicy: {
directives: {
...helmet.contentSecurityPolicy.getDefaultDirectives(),
"script-src": ["'self'", "'unsafe-inline'"],
},
},
referrerPolicy: {
policy: ["same-origin"],
},
}));
app.use(handler);
const server = http.createServer(app);
createTerminus(server, {
signals: ['SIGTERM', 'SIGINT'],
onSignal: async () => {
// Call your cleanup functions below. For example:
// db.shutdown()
},
});
server.listen(3000, () => {
console.log('Listening on port 3000');
});
Save the file and close the text editor.
Build the Project
With the project and server configurations in place, we can now build our SvelteKit project. Follow these steps to build the project:
- Build the project: Execute the following command to build the project with production variables:
npm run build
- Preview the production build: To preview the production build locally, run the following command:
npm run preview
If the build is successful, you should see a message indicating that the build was completed.
Run the Project Using PM2
To ensure the smooth operation of our SvelteKit project, we will use PM2, a process manager for Node.js applications. PM2 allows us to run applications as background processes, automatically restart them in case of failures, and monitor their performance. Follow these steps to run the project using PM2:
- Install PM2: Use the following command to install PM2 as a global package:
npm install -g pm2
- Start the SvelteKit project: Now, let’s start our SvelteKit project using the custom server file we created earlier. Execute the following command:
pm2 start server.js
If everything is set up correctly, PM2 will start the SvelteKit project as a background process.
Configure Caddy as a Reverse Proxy and Enable HTTPS Access
To provide secure access to our SvelteKit web application, we will configure Caddy, a web server that automatically generates SSL certificates for configured domain entries. Caddy acts as a reverse proxy, forwarding requests to our SvelteKit server and enabling HTTPS access. Follow these steps to configure Caddy:
- Install Caddy: Begin by adding the official Caddy repository GPG key using the following command:
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
- Add the Caddy repository: Next, add the Caddy repository to your APT sources using the following command:
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
- Update packages: Update your server packages to activate the changes made to the repository:
sudo apt update
- Install Caddy: Finally, install the Caddy web server using the following command:
sudo apt install caddy
- Configure Caddy: Back up the default Caddyfile configuration file and create a new one using the following commands:
sudo mv /etc/caddy/Caddyfile /etc/caddy/Caddyfile.ORIG sudo nano /etc/caddy/Caddyfile
In the new Caddyfile, replace the contents with the following configurations:
sveltekit.example.com { reverse_proxy localhost:3000 }
Make sure to replace “sveltekit.example.com” with your actual domain name. Save the file and exit the text editor.
- Restart Caddy: To apply the changes, restart the Caddy service:
sudo systemctl restart caddy
- Allow access through the firewall: Enable access to the SvelteKit server over HTTPS by allowing port 443 through the firewall:
sudo ufw allow 443/tcp
If you are using a different firewall, make sure to allow port 443 accordingly.
Test the SvelteKit Web Application
With everything set up, it’s time to test our deployed SvelteKit web application. Follow these steps to ensure that everything is working correctly:
- Visit your SvelteKit domain: Open a web browser and visit your configured SvelteKit domain, using the format “https://sveltekit.example.com”. Replace “sveltekit.example.com” with your actual domain name.
- Verify the application: Once the web application loads, ensure that it displays correctly in the browser. You can navigate through the application and explore its features.
- Test the Wordle game: In the top navigation menu, click on “Sverdle” or use the URL “https://sveltekit.example.com/sverdle” to access the SvelteKit Wordle game. Play the game by entering the keyword “apple” and continue guessing to complete the game sequence. For further testing, try entering the keyword “water” to complete the game sequence.
If you can access the web application without any errors or issues, congratulations! Your SvelteKit project is running correctly.
Troubleshooting
In case you encounter any issues while running your SvelteKit project, here are some common problems and their solutions:
- The SvelteKit website loads indefinitely: Check the PM2 server logs for any errors using the command
pm2 logs
. Additionally, ensure that the SvelteKit server is running on the default port 3000 specified in your configuration file. You can verify this by runningcurl 127.0.0.1:3000
. - The SvelteKit web application displays with a broken layout and no styling: This issue may occur if you’re accessing the application over HTTP instead of HTTPS. In a production environment, the helmet middleware only accepts HTTPS connections. To resolve this, configure a domain record and generate SSL certificates to enable HTTPS on your server. Alternatively, if you want to use the server without a domain record and HTTPS access, remove the helmet parts from your server.js configuration file.
Conclusion
Congratulations on successfully deploying a SvelteKit web application on an Ubuntu server! By following the steps outlined in this guide, you have gained valuable insights into the deployment process and learned how to leverage the power of SvelteKit to build efficient and high-performance web applications. Whether you’re creating a Wordle game or any other type of web application, SvelteKit and Shape.host provide you with the tools and infrastructure to deliver exceptional user experiences. Explore the endless possibilities and take your web development skills to new heights with Shape.host’s Cloud VPS services.
Remember to refer to the official SvelteKit documentation for more in-depth information and advanced features. Happy coding!