Getting started with SvelteKit

Learn how to setup Defer with SvelteKit and trigger your first background function.


Prerequisites


 

 

Install the @defer/client

  yarn add @defer/client

 

 

 

Create a defer/ folder

The Defer Platform expects to find all the background functions in the defer/ folder.

In a SvelteKit app, we recommend creating an defer/ folder as follows:

.
|-- package-lock.json
|-- package.json
|-- src/
|   |-- app.d.ts
|   |-- app.html
|   |-- defer/
|   |-- lib/
|   |-- routes/
|-- static/
|   |-- favicon.png
|   |-- robots.txt
|-- svelte.config.js
|-- tsconfig.json
`-- vite.config.ts

Notes:

  • The defer/ folder can be located anywhere in your project
  • The defer/ folder can contain nested folders

 

 

 

Write a background function

A background function is a function equivalent to a background job.

All background functions must live in the defer/ folder.

Choose how to write your first background function:

Start with the helloWorld() demo function

Let's add the following helloWorld.ts function in your defer/ folder, as follows:


src/defer/helloWorld.ts
// the `defer()` helper will be used to define a background function
import { defer } from "@defer/client"
 
// a background function must be `async`
async function helloWorld(name: string) {
	return new Promise(
	  (resolve) => {
	    setTimeout(() => {
	      console.log(`Hello ${name}!`)
	      resolve('done')
	    }, 5000)
	  }
	)
}
 
// the function must be wrapped with `defer()` and exported as default
export default defer(helloWorld)
I got a use case: a new feature or slow code to move in the background

You already have a use case? Sounds great!

Start by first creating a background function in the defer/ folder and see how to implement it depending on your use case:

src/defer/syncContacts.ts
// the `defer()` helper will be used to define a background function
import { defer } from "@defer/client"
// the `defer()` helper will be used to define a background function
import syncContacts from "../utils/syncContacts"
 
// the imported function must be wrapped with `defer()` and re-exported as default
export default defer(syncContacts)

Our background function is ready to be used; let's see how to call it from your application.

 

 

 

Call your background function

Whenever you choose to use the helloWorld() function or create your own, the following example showcasing how to call helloWorld(), from a SvelteKit /hello-world route, demonstrates how easily you can trigger a background function execution.


src/routes/hello-world/+server.ts
import helloWorld from '$defer/helloWorld';
 
/** @type {import('./$types').RequestHandler} */
export async function GET() {
	await helloWorld();
	return new Response(String('ok'));
}

How does Defer work?

If you are wondering how calling a background function triggers an execution on Defer Platform, please refer to this guide: How Defer works.



Once your SvelteKit server route is defined, please commit and push it to your branch.

Each Git commit push triggers a Build on the Defer Platform; you can go to the Defer Dashboard to check its status.

Your first successful build on the Defer Dashboard

A Defer application needs a success build to accept executions

Double check that your Defer application has at least one successful build, otherwise you won't be able to execute your background functions.

Now that your SvelteKit app contains a background function and an API route that calls it, let's ensure that your Defer token is properly configured.

 

 

 

Copy your Defer Token

Loading...

 

 

 

Configure your API deployment

Your API deployment should expose your Defer Token as an environment variable in order to get your background function deferred when called.

Set your Defer Token on Vercel
  1. Go to your Vercel Dashboard (opens in a new tab)
  2. From your project, go to settings
  3. Then, to "Environment Variables"
  4. Finally, add a new environment variable with Key as DEFER_TOKEN:
Setup your Defer Token on Vercel
Set your Defer Token on Heroku
  1. Go to your Heroku Dashboard (opens in a new tab)
  2. Select your app, and go to settings
  3. Scroll to "Config Vars" and click on "Reveal Config Vars"
  4. Finally, add a new environment variable with DEFER_TOKEN as "key":
Setup your Defer Token on Vercel
Set your Defer Token on Render
  1. Go to your Render Dashboard (opens in a new tab)
  2. Select a service
  3. Then, go to "Environment" and click on Add Environment Variable
  4. Finally, add a new environment variable with DEFER_TOKEN as "key":
Setup your Defer Token on Vercel
Set your Defer Token on Fly.io

Update your fly.toml configuration filename as follow:


fly.toml
[env]
  MY_ENV = "debug"
  DEFER_TOKEN = "<your defer token>"
Set your Defer Token on other hosting providers

Update your environment variables by adding the following:

  • key: "DEFER_TOKEN"
  • value: your Defer Token

 

 

 

Deploy

Now, with your API deployment containing your Defer Token and your project's builds ready on the Defer Platform, open your browser and test the SvelteKit route.

In the scenario of the helloWorld() background function, visit the /hello-world route.

You should see that your API answered quickly, and by going to your Defer Dashboard (opens in a new tab), you should see that your background function has 1 execution running - or finished:

Your first function on the Defer Dashboard

By clicking on see executions, you will access the executions list:

Your first successful function un on the Defer Dashboard

 

 

 

Next steps