DEV Community

MartinJ
MartinJ

Posted on • Edited on

rubbish2

1. Introduction

Thus far, all your development work has been conducted in the local server initiated in a node.js terminal session by an npm run dev command. What you now need to do is

  • "build" a version of your server that is suitable for running remotely
  • "deploy" this to a remote cloud host

2. Building your project

The "build" bit is easy. Just stop your "dev" run with a couple of "ctrl C" commands and enter the following:

npm run build
Enter fullscreen mode Exit fullscreen mode

This process uses the "Vite" build tool that will have been installed in your project automatically during the Svelte installation procedure.

This post series hasn't described Svelte's "prerendering" abilities thus far but, briefly, pre-rendering turns pages that will always generate the same output (think "book index") into static HTML in the build files. Prerendered pages will deliver startlingly fast responses in the live system

Vite starts by creating an optimized production build of both your client-side and server-side Svelte code. It then applies an "adapter" that tunes this production build for your target environment.

An adapter is a small plugin that takes the built app as input and generates output for deployment - ie for you to upload to the Cloud host. The Google Cloud provides a variety of different hosting environments. The "Google App Engine" (GAE) is the environment that is recommended in this post.

A full description of the GAE is well beyond the scope of the current series, so let me simply state that it:

  • provides a home for your "built" code
  • runs a version of the arrangement that you have previously operated with npm run dev when "poked" by a URL submitted to a web browser,
  • "scales" the resources required to run this arrangement efficiently when multiple users access it simultaneously.

In other words, the GAE is a seriously sophisticated hardware and software complex. Fortunately, unless you are doing something seriously sophisticated, you don't need to worry about this. But you do need to appreciate that this is the point at which you will have to start paying Google for its services.

If this scares you, please relax - my own billing over recent years has averaged less than $1pm.

So, moving on, as indicated above, we need to find an App Engine "adapter" for your project. While there isn't an official Google Svelte adapter, a thriving Svelte community has posted several different adaptors as open software on Git repositories.

The one I recommend is the svelte-adapter-appengine
. This can be installed with:

npm install --save-dev svelte-adapter-appengine
Enter fullscreen mode Exit fullscreen mode

To use the adapter in your project replace the current content of your svelte.config.js file with the code shown below:

import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import adapter from "svelte-adapter-appengine";
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),

kit: {
adapter: adapter(),
},
};

export default config;
Enter fullscreen mode Exit fullscreen mode

And now you can build your project with:

npm run build
Enter fullscreen mode Exit fullscreen mode

This should produce something like:

> svelte-dev@0.0.1 build
> vite build

vite v5.4.0 building SSR bundle for production...
 110 modules transformed.
page.server.js initialised
firebaseConfig.apiKey  AIzaSyDOVyss6etYIswpmVLsT6n-tWh0GZoPQhM
heartbeats undefined
heartbeats undefined
heartbeats undefined
vite v5.4.0 building for production...
 112 modules transformed.
.svelte-kit/output/client/_app/version.json                                        0.03 kB  gzip:   0.05 kB
.svelte-kit/output/client/.vite/manifest.json                                      8.92 kB  gzip:   0.94 kB

.........

.svelte-kit/output/server/entries/pages/login-with-cookie/_page.svelte.js                                  6.90 kB
.svelte-kit/output/server/chunks/internal.js                                                               7.01 kB
.svelte-kit/output/server/entries/pages/inventory-maintenance-all_client-version/_page.svelte.js           7.09 kB
.svelte-kit/output/server/index.js                                                                        93.25 kB
 built in 4.75s

Run npm run preview to preview your production build locally.
Enter fullscreen mode Exit fullscreen mode

3. Deploying your project

The npm run build has now been tucked away in your project's build folder. You can upload this to the web with a simple "deploy" command, but some initial scene-setting is required. You mst:

  • Move your project onto the Google "Blaze" pricing plan
  • Configure your project's use of AppEngine
  • Install the GCloud tool that performs the deployment
  • Give your Gmail account the App Engine Deployer (roles/appengine.deployer) role in the Cloud console's IAM module.

3.1 Moving a project onto "Blaze" pricing

On the Firebase console's "Project Overview" page for your project, mouse over the tool stack in the left-hand column and note, at the bottom of this, a "Related Development Tools" section showing that the project is currently on the "Spark" free plan. Click the "upgrade" button next to this and then "Select plan" on the "Blaze" popup that now appears.

This will invite you to register a credit card and set a monthly limit on the amount that Google can charge you. My limit is set at $2 and has never been breached

3.2 Configuring App Engine for your project

You do this through the Google Cloud console. This provides an umbrella for the numerous "sub-consoles" that let you configure and administer individual Cloud services.

Sadly, the App Engine isn't listed on the "pinned" Quick access list displayed on the IAM "Welcome" page. But you can easily find it by entering "app engine" in the search box and clicking the "Search" button. Select "Dashboard" from the list of consoles and documents thus revealed.

Now check that the name of your project is showing in the "triple dot" box at the top left of the screen and click the "Create application" button". This will invite you to select a Region (server location) for your project. You'll probably want to use the same regions as you are using for your database. Now, leaving the service account field set to "App Engine Default Service Account", press "Done" to complete the setup

3.3 Setting the App Engine/App Engine Deployer role in IAM

The IAM (Identity and Access Management console) lists the "roles" that have been issued to "principals" for your project. Principals may be people (identified by their Google accounts) or abstract system entities (identified by service accounts). If your Google email doesn't appear as an IAM principal with the "App Engine Deployer" role, your attempts to run a deploy command will be rejected. To access IAM, return to the Cloud console's welcome page and select "IAM and admin" from the Quick access list.

Now click the "Grant Access" button, enter your Gmail ID in the "new principals" field and then, in the Role field, scroll down to "App Engine" in the left-hand panel and select "App Engine Deployer" in the right-hand panel". "Save" this and you're done.

3.4 Installing the Gcloud tool on your system

The Gcloud tool enables you to to run a terminal gcloud command to deploy your software to your App Engine host. The installation procedure for the Google Cloud CLI (Command Line Interface) is documented at Google CLI Installation.

Windows users should navigate here to the "Windows" submenu where the document provides a "download" button that creates a Windows Installer file in the download directory. Click this and accept the pre-selected options. The documentation suggests that you need to explicitly request the inclusion of the modules necessary to support App Engine but, at the time of writing (Sept 2024), this no longer appears to be the case.

3.5 Deploying your webapp

This is a big moment! Run the following command in your VSCode terminal session:

deploy --project [project-id] build/app.yaml
Enter fullscreen mode Exit fullscreen mode

Here, [project-id] is the uniquely qualified version of your project name that Google generated when you initialised your project in post "???". For example, my own "svelte-dev" project is deployed with deploy --project svelte-dev-81286 build.yaml

The build.yaml file is an interesting feature of the command. This is a configuration file that was by the preceding Vite "build". It tells gcloud where to find the various artefacts and configurations in the "build" folder.

If all goes well you should see something like the following:

Beginning deployment of service [default]...
#============================================================#
#= Uploading 19 files to Google Cloud Storage                =#
#============================================================#
File upload done.
Updating service [default]...-WARNING: *** Improve build performance by generating and committing package-lock.json.

Updating service [default]...done.
Setting traffic split for service [default]...done.
Deployed service [default] to [https://svelte-dev-81286.nw.r.appspot.com]

You can stream logs from the command line by running:
  $ gcloud app logs tail -s default

To view your application in the web browser run:
  $ gcloud app browse --project=svelte-dev-81286
Enter fullscreen mode Exit fullscreen mode

The webapp can now be run on the web at https://svelte-dev-81286.nw.r.appspot.com

4. Get a custom domain

Once you are ready to go fully live, you will probably want something snappier than https://svelte-dev-81286.nw.r.appspot.com. Commercial platforms such as SquareSpace can let you choose a market-friendly "custom URL"for a very reasonable annual fee (currently around $20pa). Another reason for using a custom URL is that this appears to enable search engines to index your site.

Once you've purchased your custom URL, you then link this to the raw App Engine URL generated by your build. Here's a brief description of the procedure:

4.1 Verify Domain Ownership:

  • In the left-hand menu of the App Engine dashboard (see above), navigate to Settings > Custom Domains.
  • Click Add a Custom Domain.
  • If your domain is not yet verified Google will guide you through the steps to verify it. This typically involves adding a TXT record in your domain’s DNS settings.

4.2 Map the Domain to Your App:

Once the domain is verified, you can map it to your App Engine application:

  • In the Custom Domains section of App Engine Settings, select your custom domain from the list of verified domains.
  • Specify the subdomains (like www.example.com or just example.com) that you want to link to your app.
  • Google Cloud will provide the DNS records (usually CNAME and A records) required to configure in your domain registrar’s settings.

4.3 Configure DNS Settings:

  • Go to your domain registrar (eg SquareSpace) and find the DNS settings for your domain.
  • Add the DNS records that Google provided during the domain mapping process. These usually include:
  • CNAME record: For subdomains like www, this points to ghs.googlehosted.com.
  • A records: For the root domain (like example.com), this will point to specific IP addresses provided by Google Cloud.

4.4 Set Up SSL (Enable use of HTTPS addresses):

  • Google Cloud automatically provisions SSL certificates for your custom domain. If you visit the Custom Domains section after mapping your domain, you'll see the SSL status as "Provisioning." It usually takes a few minutes to complete.
  • Once complete, your app will be accessible over HTTPS.

4.5 Wait for DNS Propagation:

  • DNS changes can take some time to propagate, so your custom domain might not work immediately. This process can take a few minutes to several hours, depending on your registrar.

Pre-rendering and the daily-rebuid idea
SEO post
AI notes

When things go wrong

A moment's thought will tell you that, after deployment, log messages on your live pages can no longer go to your project's local terminal session. Instead, they go to the Google Cloud rather than and I'm sorry to say this means you'll need to raise your game if you still need to see them.

Here's the address for the Google Logs Explorer. Check that your project name is displayed in the "three dot" field at top left and try not be too overwhelmed by the dizzying array of menus and sub-windows.

Your problem is that Google logs absolutely everything that happens on your project, so you'll see information about project build activity and page startup as well as your own log messages. Furthermore, it records this information in minute detail back to the dawn of time. Finding what you want can be a challenge.

To help you through this maze, the explorer allows you to filter it in various ways. For example, you can opt to see only log entries "console.log" message for "App Engine" processes by checking the "GAE" and "info" in the "Resource Type" box (if this doesn't appear, toggle the button with a sort of square box icon on the rhs of the screen between its "expand" and its "collapse" state). Additionally - and I find this is the technique I use most often - you can use the "Log fields" box to see only log messages with specific content. So, if I was looking for console.log("productName = " + productName) messages I would place a textPayload:"productName" entry in the Log Fields box.

Additionally, of course, you can filter the log search to a given period in various ways - start/finish or "around", for example. Click the console window with the little clockface icon at the top-left of the screen to access these options.

Here's a shot of the Logs Explorer displaying a log message for one of my deployed pages:
????

Top comments (0)