Upstash as SvelteKit Real-time Game Database
Tags: sveltekit, redis, webdev
Published: 2023-07-11 08:49:33

---
title: "Upstash as SvelteKit Real-time Game Database"
published: "true"
description: "Upstash as SvelteKit Real-time Game Database 💿 how you can add a serverless database to a multiplayer ♟️ game built with Svelte."
tags: "sveltekit, redis, webdev"
canonical_url: "https://rodneylab.com/upstash-sveltekit-realtime-game-database/"
cover_image: "https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nygfeevbiwu1pokf91qb.png"
---

## 🪢 Using Upstash Redis with SvelteKit

In this post, we look at how you can use Upstash as a  SvelteKit real-time game database.  The post continues a series on building a simple, real-time, serverless strategy game.

Upstash provide serverless Redis, which is exactly what we use for the database here.  You will typically opt for Redis, over another database offering, like PostgreSQL or SQLite, when you want quick access to string records, or database records which can easily be serialized to a string. In fact, Redis is often used for server-side caching, allowing faster responses to server requests.  I have already written a couple of pieces on <a href="https://upstash.com/blog/getting-started-astro-redis?utm_source=Rodney1">using Upstash Redis with Astro</a> and <a href="https://upstash.com/blog/redis-and-performance-api?utm_source=Rodney2">Deno Fresh</a>, so have a look at those if they are your preferred frameworks.

For the game, I use Upstash to store metadata on existing games, including identifiers for the players in each game.  In this short post, we see how you can integrate Upstash Redis with SvelteKit.

## 🧱 What are we Building?

![Upstash as SvelteKit Real-time Game Database: screenshot shows complete game, with player 2 having won, claiming 4 (blue) squares, while player 1 only has two (orange) squares.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5vmx40x09eehxn3gkqv.png)

We won&rsquo;t build the app from scratch, though you can find a link to the project open-source repo, if you want to play around with it.  Here, we just focus on the steps for integrating Upstash into an existing SvelteKit Server-side Rendered (**SSR**) app.

## 🔥 Adding Serverless Upstash to your SvelteKit App

1. Add the <code>@upstash/redis</code> package to your SvelteKit project:
    ```shell
    pnpm add -D @upstash/redis
    ```
1. You can create a Redis instance by importing `Redis` as a named import from `@upstash/redis`:
    ```typescript
    import { UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN } from '$env/static/private';

    import { Redis } from '@upstash/redis';

    const redis = new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN });
   ```
    For an SSR app, to save including this code on every `+page.server.ts` file, you can add the setup, once, to `src/hooks.server.ts`, placing the Redis instance on request `event.locals`:
    ```typescript
    import { UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN } from '$env/static/private';

    import { Redis } from '@upstash/redis';

    export const handle = async ({ event, resolve }) => {
	    event.locals.redis = new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN });

    	return resolve(event);
    };
    ```
    Then, in a `+page.server.ts` file, within the `load` function access the Redis instance via `locals`:
    ```typescript
        export async function load({ locals }) {
	        const game = (
		        await locals.redis.hget(REDIS_HASHSET_KEY, gameId)
	    );

          /* TRUNCATED... */
        };
    ```
    This works within `+page.server.ts` files, where the `locals` object is available.  Use the previous code with other files.  Either way, remember to update the <code>.env</code> file with your Upstash credentials.
3. You can now create, read, update and delete records, using a key as a collection identifier.  For the game, I use <a href="https://redis.io/docs/data-types/hashes/">Redis hashes</a>, which allow <strong>constant time</strong> get and set operations.  The game collection contains records; each an object with two fields.  I run hashset <code>Create</code> and <code>Read</code> operation using the <code>redis</code> object thus:
    ```typescript
    // Create/set:
    await locals.redis.hset(REDIS_HASHSET_KEY, {
	    [gameId]: JSON.stringify({ player1, player2 })
    });
 
    // Read/get:
    const game = await locals.redis.hget(
	    REDIS_HASHSET_KEY, gameId
    );
```

Here are some examples of Redis Hashset Create, Read, Update and Delete (<strong>CRUD</strong>) operations, using the Upstash API:
- **Create**
    ```typescript
    await redis.hset(REDIS_HASHSET_KEY, {
     record_key: record_value
    });
    ```
- **Read**
    ```typescript
    await redis.hget(REDIS_HASHSET_KEY, record_key);
    ```
- **Update**
    ```typescript
    await redis.hset(REDIS_HASHSET_KEY, {
        record_key: record_value
    });
    ```
- **Delete**
    ```typescript
    await redis.hset(REDIS_HASHSET_KEY, record_key);
    ```

That should be enough to get you going, but please let me know if anything needs more explanation.  Drop a comment below or reach out via <a href="https://rodneylab.com/contact/">your preferred contact method</a>.

## 🙌🏽 Upstash as SvelteKit Real-time Game Database: Wrapping Up

In this post, on Upstash as SvelteKit real-time game database, we saw how you can use Redis Upstash with SvelteKit.  More specifically, we saw:

- **how to add Upstash Redis dependencies** to your SvelteKit project;
- **how to create a Redis instance** ; and
- some **basic CRUD operations with the Upstash API**.

Please <a aria-label="Open the Rodney Lab Git Hub repo" href="https://github.com/rodneylab/sveltekit-ably-realtime-game">see the full repo code on the Rodney Lab GitHub repo</a>. I do hope you have found this post useful and can use the code in your own SvelteKit project.  Let me know if you have any suggestions for improvements to the game.  Drop a comment below or <a href="https://rodneylab.com/contact/">reach out on other channels</a>.

## 🙏🏽 Upstash as SvelteKit Real-time Game Database: Feedback

If you have found this post useful, see links below for further related content on this site. I do hope you learned one new thing from the video. Let me know if there are any ways I can improve on it. I hope you will use the code or starter in your own projects. Be sure to share your work on Twitter, giving me a mention, so I can see what you did. Finally, be sure to let me know ideas for other short videos you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please <a aria-label="Support Rodney Lab via Buy me a Coffee" href="https://rodneylab.com/giving/">consider supporting me through Buy me a Coffee</a>.

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via <a href="https://twitter.com/messages/compose?recipient_id=1323579817258831875">@askRodney</a> on Twitter and also <a aria-label="Contact Rodney Lab via Telegram" href="https://t.me/askRodney">askRodney on Telegram</a>. Also, see <a aria-label="Get in touch with Rodney Lab" href="https://rodneylab.com/contact/">further ways to get in touch with Rodney Lab</a>. I post regularly on <a aria-label="See posts on svelte kit" href="https://rodneylab.com/tags/sveltekit/">SvelteKit</a> as well as <a href="https://rodneylab.com/tags/seo/" aria-label="See posts on search engine optimisation">Search Engine Optimization</a> among other topics. Also, <a aria-label="Subscribe to the   Rodney Lab newsletter" href="https://newsletter.rodneylab.com/issue/latest-issue">subscribe to the newsletter to keep up-to-date</a> with our latest projects.