DEV Community

Daisy Auma
Daisy Auma

Posted on

Build a Daily Game for Reddit with Devvit, React and Redis

By the end of this tutorial, you'll have a daily game running inside a Reddit post. Players make one guess a day, see how they did against everyone else, and a new round posts itself every morning.

We'll build it the way I built Trendline, my entry for Reddit's Game of the Day hackathon. In Trendline, you see the first part of a real chart, draw where the line goes next, then see what actually happened next to the crowd's average guess. The full code is on GitHub, and every snippet below comes from it.

Trendline's reveal screen: your guess, the crowd's average and what actually happened
What we're building toward: a reveal that compares your guess with the crowd's. Player names are blurred.

How a Reddit game works

Think of a Devvit app as a tiny website that lives inside a Reddit post. It has a front end (React, in our case), a small server, and its own Redis database. Reddit hosts all three, so there's nothing to deploy to a cloud provider and no database to set up.

The post has two views:

  • The preview that people see while scrolling their feed
  • The expanded game that opens when they tap to play

The server knows which post it's running in and who is playing, so you don't need to build any login.

Prerequisites

  • Node.js, at the version in the template's .nvmrc file
  • Git
  • A Reddit account
  • VS Code or any editor, with its terminal
  • The Devvit CLI, which the template installs for you (I used version 0.15.4)

Step 1: Create the project from Reddit's React template

Reddit maintains a starter project with React, Vite, Hono and TypeScript already wired together. Let's clone it and install its packages:

git clone https://github.com/reddit/devvit-template-react my-daily-game
cd my-daily-game
npm install
Enter fullscreen mode Exit fullscreen mode

You should see added ... packages at the end. Warnings about deprecated packages are normal and safe to ignore.

The template comes with its own git history pointing at Reddit's repository. If you plan to push your game to GitHub, start fresh:

rm -rf .git
git init
git branch -M main
Enter fullscreen mode Exit fullscreen mode

Step 2: Log in and register the app

Log in to Reddit from the terminal:

npx devvit login
Enter fullscreen mode Exit fullscreen mode

A browser tab opens. Log in, click Allow, then come back to the terminal.

Now start a playtest:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Two things tripped me up here, so let's handle them before they happen.

"Please finish setting up your developer account." Choose Open developer account page in browser, accept the developer terms, then come back and choose I have finished setting up my developer account; check again.

"Your app doesn't exist yet." Devvit reads your app's name from devvit.json. If that name was never registered with Reddit, playtest refuses to run, and npx devvit init may say the app is already initialized. Register it properly with:

npx devvit init --force
Enter fullscreen mode Exit fullscreen mode

When it's done, npm run dev should print something like:

✓ Playtest ready
➜ URL: https://www.reddit.com/r/your_app_dev/?playtest=your-app
Enter fullscreen mode Exit fullscreen mode

Devvit creates a private test subreddit for you and installs the app there. Leave this terminal running. Every time you save a file, it rebuilds and uploads, and you refresh the page to see the change.

Step 3: Configure devvit.json

devvit.json tells Reddit what your app contains. Here's Trendline's, with the parts that matter for a daily game:

{
  "$schema": "https://developers.reddit.com/schema/config-file.v1.json",
  "name": "your-app-name",
  "post": {
    "dir": "dist/client",
    "entrypoints": {
      "default": { "inline": true, "entry": "splash.html" },
      "game": { "entry": "game.html" }
    }
  },
  "server": { "dir": "dist/server", "entry": "index.cjs" },
  "menu": {
    "items": [
      {
        "label": "Post today's Trendline",
        "description": "Create today's Trendline chart post",
        "location": "subreddit",
        "forUserType": "moderator",
        "endpoint": "/internal/menu/post-create"
      }
    ]
  },
  "triggers": { "onAppInstall": "/internal/triggers/on-app-install" },
  "scheduler": {
    "tasks": {
      "daily-post": {
        "endpoint": "/internal/scheduler/daily-post",
        "cron": "5 0 * * *"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Here's what each part does:

  • post.entrypoints defines the two views. default is the preview, shown inline in the feed. game is the expanded view.
  • server points at your built server code.
  • menu adds a moderator-only menu item to the subreddit, handy for posting a round by hand.
  • triggers runs code when the app is installed. We'll use it to create the first post.
  • scheduler runs a task on a cron schedule. 5 0 * * * means 00:05 UTC every day.

Keep the name that Devvit registered for you in Step 2.

Step 4: Store one guess per player in Redis

A daily game needs one rule above all: one guess per player per day. The tricky part is a player double tapping the submit button. Two requests arrive at almost the same moment, both check "has this player played?", both see "no", and both save.

Redis has an atomic counter that solves this. incrBy increases a number and returns the new value in one step, so only one request can ever see 1:

const keys = {
  playedFlag: (day: number, userId: string) => `day:${day}:played:${userId}`,
  guess: (day: number, userId: string) => `day:${day}:guess:${userId}`,
  sums: (day: number) => `day:${day}:sums`,
  count: (day: number) => `day:${day}:count`,
  scores: (day: number) => `day:${day}:scores`,
};

export async function saveGuess(
  day: number,
  userId: string,
  username: string,
  guess: number[]
): Promise<{ ok: true; streak: Streak } | { ok: false }> {
  // incrBy is atomic, so two quick taps can't both count.
  const first = (await redis.incrBy(keys.playedFlag(day, userId), 1)) === 1;
  if (!first) return { ok: false };

  const chart = chartForDay(day);
  const score = scoreGuess(chart, guess);
  await redis.set(keys.guess(day, userId), JSON.stringify({ guess, score }));
  for (let i = 0; i < guess.length; i++) {
    await redis.hIncrBy(keys.sums(day), String(i), toFraction(chart, guess[i]!));
  }
  await redis.incrBy(keys.count(day), 1);
  await redis.zAdd(keys.scores(day), { member: username, score });
  const streak = await updateStreak(userId, day);
  return { ok: true, streak };
}
Enter fullscreen mode Exit fullscreen mode

redis is imported from @devvit/web/server. Every key includes the day, so each round's data stays separate, and old posts keep their own results.

The last two lines feed the leaderboard and streaks. zAdd puts the score in a sorted set, which Redis keeps in order for you.

Step 5: Build the crowd average from running totals

The obvious way to show the crowd's average is to read every guess and average them. That gets slower with every player.

Instead, look at the hIncrBy loop in the code above. Each guess is converted to a position on the chart between 0 and 1, scaled to a whole number, and added to a running total for each point on the line. Together with the player count, that's everything you need:

const players = await playerCount(day);
let crowd: number[] | null = null;
if (players > 0) {
  const sums = await redis.hGetAll(keys.sums(day));
  crowd = actual.map((_, i) =>
    fromFraction(chart, Number(sums[String(i)] ?? 0) / players)
  );
}
Enter fullscreen mode Exit fullscreen mode

Two Redis reads, however many people have played. The conversion helpers are short:

export const FRACTION_SCALE = 10000;

export function toFraction(chart: Chart, value: number): number {
  const f = (value - chart.yMin) / (chart.yMax - chart.yMin);
  return Math.round(Math.min(1, Math.max(0, f)) * FRACTION_SCALE);
}

export function fromFraction(chart: Chart, scaled: number): number {
  return chart.yMin + (scaled / FRACTION_SCALE) * (chart.yMax - chart.yMin);
}
Enter fullscreen mode Exit fullscreen mode

Storing whole numbers matters because hIncrBy adds integers. Positions between 0 and 10,000 keep plenty of precision.

Step 6: Serve the game from a Hono API

The server is a Hono app. Routes under /api are called by your React client. Routes under /internal are called by Reddit itself, for the menu, triggers and scheduler:

import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { createServer, getServerPort } from '@devvit/web/server';
import { api } from './routes/api';
import { menu } from './routes/menu';
import { scheduler } from './routes/scheduler';
import { triggers } from './routes/triggers';

const app = new Hono();
const internal = new Hono();

internal.route('/menu', menu);
internal.route('/triggers', triggers);
internal.route('/scheduler', scheduler);

app.route('/api', api);
app.route('/internal', internal);

serve({
  fetch: app.fetch,
  createServer,
  port: getServerPort(),
});
Enter fullscreen mode Exit fullscreen mode

The game needs two endpoints. /api/init loads everything the client needs when the post opens. context tells you which post this is and who is playing:

api.get('/init', async (c) => {
  try {
    const { postId, userId } = context;
    if (!postId) {
      return c.json<ErrorResponse>({ status: 'error', message: 'No post in context' }, 400);
    }
    const day = await getPostDay(postId);
    const username = (await reddit.getCurrentUsername()) ?? null;
    const reveal = userId ? await buildReveal(day, userId) : null;
    return c.json<InitResponse>({
      day,
      chart: publicChart(chartForDay(day)),
      players: await playerCount(day),
      username,
      loggedIn: Boolean(userId),
      reveal,
      streak: await getStreak(userId),
    });
  } catch (error) {
    console.error('init failed', error);
    return c.json<ErrorResponse>({ status: 'error', message: 'Could not load the game' }, 400);
  }
});
Enter fullscreen mode Exit fullscreen mode

Notice publicChart. It sends only the part of the chart the player is allowed to see. The answer stays on the server until they've played, so nobody can find it in the browser's network tab.

/api/guess validates the guess and saves it:

api.post('/guess', async (c) => {
  try {
    const { postId, userId } = context;
    if (!postId || !userId) {
      return c.json<ErrorResponse>({ status: 'error', message: 'Log in to play' }, 401);
    }
    const body = await c.req.json<GuessRequest>();
    const day = await getPostDay(postId);
    const chart = chartForDay(day);
    const expected = hiddenValues(chart).length;
    const guess = body.guess;
    if (
      body.day !== day ||
      !Array.isArray(guess) ||
      guess.length !== expected ||
      guess.some((v) => typeof v !== 'number' || !Number.isFinite(v))
    ) {
      return c.json<ErrorResponse>({ status: 'error', message: 'That guess looks incomplete' }, 400);
    }
    const clamped = guess.map((v) => Math.min(chart.yMax, Math.max(chart.yMin, v)));
    const username = (await reddit.getCurrentUsername()) ?? 'anonymous';
    const saved = await saveGuess(day, userId, username, clamped);
    if (!saved.ok) {
      return c.json<ErrorResponse>({ status: 'error', message: "You've already played this one" }, 409);
    }
    const reveal = await buildReveal(day, userId);
    return c.json<GuessResponse>({ reveal: reveal!, streak: saved.streak });
  } catch (error) {
    console.error('guess failed', error);
    return c.json<ErrorResponse>({ status: 'error', message: 'Could not save your guess' }, 400);
  }
});
Enter fullscreen mode Exit fullscreen mode

Never trust the client. The server checks the day, the length of the guess, and that every value is a real number, then clamps values to the chart's range before saving.

Step 7: Build the React client

The client is two small React apps, one per entrypoint. Each calls /api/init when it loads.

The preview in the feed should be light and make sense in two seconds. Its job is to get people to tap. requestExpandedMode opens the game entrypoint you defined in devvit.json:

import { requestExpandedMode } from '@devvit/web/client';

function Splash() {
  const [data, setData] = useState<InitResponse | null>(null);

  useEffect(() => {
    loadGame().then(setData).catch(() => setData(null));
  }, []);

  return (
    <main className="splash">
      <p className="kicker">Trendline{data ? ` #${data.day + 1}` : ''}</p>
      <h1>{data?.chart.title ?? 'Where does the line go next?'}</h1>
      {data && <Chart chart={data.chart} />}
      <button onClick={(e) => requestExpandedMode(e.nativeEvent, 'game')}>
        {data?.reveal ? `You scored ${data.reveal.score}. See the results` : 'Draw the rest'}
      </button>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

The button text changes once you've played, so returning players go straight to their results.

Calling the API from the client is a plain fetch to a relative path. Devvit routes it to your server:

async function request<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(path, {
    ...init,
    headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
  });
  const body = (await res.json()) as T | ErrorResponse;
  if (!res.ok) throw new Error((body as ErrorResponse).message ?? 'Something went wrong');
  return body as T;
}

export const loadGame = () => request<InitResponse>('/api/init');

export const sendGuess = (day: number, guess: number[]) =>
  request<GuessResponse>('/api/guess', {
    method: 'POST',
    body: JSON.stringify({ day, guess }),
  });
Enter fullscreen mode Exit fullscreen mode

Step 8: Post a new round every day

A daily game needs a daily post. One function creates it and remembers which day it belongs to:

import { reddit } from '@devvit/web/server';
import { chartForDay, dayNumber } from '../../shared/game';
import { setPostDay } from './store';

export const createPost = async (day: number = dayNumber()) => {
  const chart = chartForDay(day);
  const post = await reddit.submitCustomPost({
    title: `Trendline #${day + 1}: ${chart.title}. Where does the line go next?`,
  });
  await setPostDay(post.id, day);
  return post;
};
Enter fullscreen mode Exit fullscreen mode

Storing the day against the post ID is what keeps old posts playable. Yesterday's post still loads yesterday's chart.

The scheduler task from devvit.json calls it every day:

import { Hono } from 'hono';
import { createPost } from '../core/post';

export const scheduler = new Hono();

scheduler.post('/daily-post', async (c) => {
  try {
    const post = await createPost();
    console.log(`Daily Trendline post created: ${post.id}`);
    return c.json({ status: 'success' }, 200);
  } catch (error) {
    console.error(`Daily post failed: ${error}`);
    return c.json({ status: 'error' }, 400);
  }
});
Enter fullscreen mode Exit fullscreen mode

The menu item and install trigger call the same createPost function, so there's one place to change if you rename your posts.

To decide which day it is, count days since a fixed start date in UTC:

export const EPOCH_UTC = Date.UTC(2026, 10, 25);
const DAY_MS = 24 * 60 * 60 * 1000;

export function dayNumber(now: number = Date.now()): number {
  return Math.floor((now - EPOCH_UTC) / DAY_MS);
}
Enter fullscreen mode Exit fullscreen mode

Set EPOCH_UTC to your own launch date. Note that JavaScript months start at 0, so 10 is November.

Step 9: Playtest, deploy and install

While npm run dev is running, open the playtest URL and play your game. Check the preview, the expanded view, and what happens when you submit twice.

When you're happy with it, upload a release version:

npm run deploy
Enter fullscreen mode Exit fullscreen mode

Then create a public subreddit for your game and install the app there:

npx devvit install YourSubredditName
Enter fullscreen mode Exit fullscreen mode

Leave out the r/. The install trigger creates the first post straight away.

One thing I didn't expect: Reddit held my app's first posts until I approved them as the subreddit's moderator. New app accounts don't have much history, so check your Mod Queue after each daily post until your app's posts go up on their own.

Recap

You now have a daily Reddit game with:

  • Two views: a light preview in the feed and an expanded game
  • One guess per player per day, enforced with an atomic Redis counter
  • A crowd average built from running totals, so it stays fast as players grow
  • A new post every day from the Devvit scheduler, plus a moderator menu item to post by hand

The same pattern works for much more than charts. A daily poll where you guess how the crowd will vote, a prediction game for sports results, or a community challenge that builds up over a week all need the same pieces: one action per player, a shared total, and a fresh post each day.

The complete code for Trendline is on GitHub, and you can play today's chart at r/TrendlineGame.

Top comments (0)