🪢 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?
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
-
Add the
@upstash/redis
package to your SvelteKit project:
pnpm add -D @upstash/redis
-
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, tosrc/hooks.server.ts
, placing the Redis instance on requestevent.locals
:
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 theload
function access the Redis instance vialocals
:
export async function load({ locals }) { const game = ( await locals.redis.hget(REDIS_HASHSET_KEY, gameId) ); /* TRUNCATED... */ };
This works within
+page.server.ts
files, where thelocals
object is available. Use the previous code with other files. Either way, remember to update the.env
file with your Upstash credentials. -
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
andRead
operation using theredis
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.
🙌🏽 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: 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.
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.
Top comments (0)