Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

Upstash as SvelteKit Real‑time Game Database 💿 # Upstash as SvelteKit Real-time Game Database 💿 #

blurry low resolution placeholder image Svelte Real-time Multiplayer Game
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. SvelteKit SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Upstash as SvelteKit Real‑time Game Database 💿 #

Published: 2 years ago
4 minute read
Gunning Fog Index: 5.7
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

🪢 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 using Upstash Redis with Astro  and Deno Fresh , 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? #

blurry low resolution placeholder image 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.
Upstash as SvelteKit Real-time Game Database: Sqvuably Game

We won’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 #

How to add Upstash Redis to a SvelteKit SSR app #

  1. Add the @upstash/redis package to your SvelteKit project:
        
    pnpm add -D @upstash/redis
  2. You can create a Redis instance by importing Redis as a named import from @upstash/redis:
        
    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:
    src/hooks.server.ts
    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:
    src/routes/+page.server
    typescript
        
    1 export async function load({ locals }) {
    2 const game = (
    3 await locals.redis.hget(REDIS_HASHSET_KEY, gameId)
    4 );
    5
    6 /* TRUNCATED... */
    7 };
    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 .env 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 Redis hashes, which allow constant time get and set operations. The game collection contains records; each an object with two fields. I run hashset Create and Read operation using the redis object thus:
        
    // 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 (CRUD) operations, using the Upstash API:
    • Create
          
      await redis.hset(REDIS_HASHSET_KEY, {
      record_key: record_value
      });
    • Read
          
      await redis.hget(REDIS_HASHSET_KEY, record_key);
    • Update
          
      await redis.hset(REDIS_HASHSET_KEY, {
      record_key: record_value
      });
    • Delete
          
      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 your preferred contact method.

🗳 Poll #

How will you implement server-side caching on your next app?
Voting reveals latest results.

🙌🏽 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 see the full repo code on the Rodney Lab GitHub repo . 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 reach out on other channels.

🏁 Upstash as SvelteKit Real‑time Game Database: Summary #

How can you avoid repeating database initialization code in a SvelteKit SSR app? #

The SvelteKit `hooks.server.ts` file is a great place to initialize databases. It lets you run code on each server request, adding data that you want to be access in the endpoint logic. It is essentially middleware. Add a `src/hooks.server.ts` file to your project, then export a handle function. Within the body of your handle function, add your database instance to the `event.locals` object. For example, we saw, working with Upstash Redis, you might set `event.locals.redis = new Redis();`. Then, in your `+page.server.ts files`, you will have access to the initialized database instance via the `locals` object.

How can you add Redis to a serverless app? #

Upstash offers a serverless Redis service with Node and Deno APKs. The node package is `@upstash/redis`, and provides access to expected Redis APIs. That is, without you needing to host a long-running Redis instance.

When would you use a Redis hash? #

Redis hashes allow you to store key-value pairs in a named hash collection. Creating, reading, updating and deleting a single record are all constant-time operations. By contrast, lists have linear performance for set and update operations, though accessing the head (or first) entry is a constant-time operation. With capacity for over 4 billion key-value pairs, hashes provide plenty of capacity for common use cases.

🙏🏽 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 consider supporting me through Buy me a Coffee.

blurry low resolution placeholder image ask Rodney X (formerly Twitter) avatar

Rodney

@askRodney

Just dropped a new post on using

@upstash with ❤️SvelteKit as a database in a real-time game.

Hope you find it useful!#learnSvelte #upstashGuyHesBeenLivingInHisUpstashWorldhttps://t.co/dNI1sMIvx3

— Rodney (@askRodney) June 28, 2023

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 @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as Search Engine Optimization among other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
SVELTEKIT

Related Posts

blurry low resolution placeholder image SvelteKit Ably: Sqvuably Real-Time Game ♟️

SvelteKit Ably: Sqvuably Real-Time Game ♟️

sveltekit
gaming
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.