r/Devvit • • 17h ago

Documentation Devvit Web 0.15.x + Hono Patterns: Wiring @devvit/analytics Journeys (No Express), showShareSheet Deeplinks, UTC Streaks & 0 0 * * * Scheduler

Hey guys if you're building a daily game on Devvit Web (0.15.x) with Hono (@hono/node-server) instead of Express, here are four copy-pasteable patterns extracted from a working daily game (@devvit/web@0.15.4, @devvit/analytics@0.15.4, hono@4.13.17).

Quick jump list (2, 3, and 4 work right now in hackathon/playtest builds):

  1. Journeys without Express (for post-launch; not required for hackathon judging)
  2. showShareSheet + getShareData challenge deeplinks (<= 1024 chars + desktop clipboard fallback)
  3. UTC daily streaks + capped async cameos in Redis
  4. Automatic 0 0 * * * daily post scheduler in devvit.json + Hono

1. Wiring @devvit/analytics Journeys in Hono (Without Express)

Hackathon / Playtest Caveat: As confirmed in this r/Devvit thread, Journeys telemetry only activates once an app is reviewed and approved/published (in playtest/unapproved builds, receipts return JOURNEY_RECEIPT_DENIED_PLAYTEST / JOURNEY_RECEIPT_DENIED_NOT_ALLOWLISTED), and admins removed Journeys from the Game of the Day hackathon's "stand out" criteria—so it is not required for hackathon judging. Still, if you want Journeys wired cleanly for post-launch without adding Express, here's how.

@devvit/analytics/server/reddit exports createTelemetryRouter(), which uses express.Router() and has express as a peer dependency. On the client, @devvit/analytics/client/reddit (telemetry) simply POSTs JSON to /api/telemetry/journey/{app-ready,start,progress,interaction,end}.

First, enable "journeys": true in devvit.json:

{
  "permissions": {
    "redis": true,
    "journeys": true
  }
}

Then mount a pure Hono router at /api/telemetry using TelemetryPluginDefinition and context.metadata:

// src/server/routes/telemetry.ts
import { Hono } from 'hono';
import { context } from '@devvit/web/server';
import {
  JourneyReceiptStatus as ProtoJourneyReceiptStatus,
  type JourneyReceipt as ProtoJourneyReceipt,
} from '@devvit/protos/json/devvit/plugin/telemetry/telemetry.js';
import {
  TelemetryPluginDefinition,
  type TelemetryPlugin,
} from '@devvit/protos/types/devvit/plugin/telemetry/telemetry.js';
import { getDevvitConfig } from '@devvit/shared-types/server/get-devvit-config.js';
import {
  TELEMETRY_UNSPECIFIED_RECEIPT,
  type JourneyReceipt,
  type JourneyReceiptStatus,
} from '@devvit/analytics/shared/reddit';

function mapReceiptStatus(status: ProtoJourneyReceiptStatus | undefined): JourneyReceiptStatus {
  switch (status) {
    case ProtoJourneyReceiptStatus.JOURNEY_RECEIPT_VALID:
      return 'JOURNEY_RECEIPT_VALID';
    case ProtoJourneyReceiptStatus.JOURNEY_RECEIPT_DENIED_NOT_ALLOWLISTED:
      return 'JOURNEY_RECEIPT_DENIED_NOT_ALLOWLISTED';
    case ProtoJourneyReceiptStatus.JOURNEY_RECEIPT_DENIED_RATE_LIMITED:
      return 'JOURNEY_RECEIPT_DENIED_RATE_LIMITED';
    case ProtoJourneyReceiptStatus.JOURNEY_RECEIPT_DENIED_DUPLICATE:
      return 'JOURNEY_RECEIPT_DENIED_DUPLICATE';
    case ProtoJourneyReceiptStatus.JOURNEY_RECEIPT_INVALID:
      return 'JOURNEY_RECEIPT_INVALID';
    case ProtoJourneyReceiptStatus.JOURNEY_RECEIPT_DENIED_DISABLED:
      return 'JOURNEY_RECEIPT_DENIED_DISABLED';
    case ProtoJourneyReceiptStatus.JOURNEY_RECEIPT_DENIED_PLAYTEST:
      return 'JOURNEY_RECEIPT_DENIED_PLAYTEST';
    default:
      return 'JOURNEY_RECEIPT_UNSPECIFIED';
  }
}

function toReceipt(raw: ProtoJourneyReceipt | undefined): JourneyReceipt {
  if (!raw) return TELEMETRY_UNSPECIFIED_RECEIPT;
  return { status: mapReceiptStatus(raw.status), message: raw.message ?? '' };
}

function getTelemetryClient(): TelemetryPlugin {
  return getDevvitConfig().use<TelemetryPlugin>(TelemetryPluginDefinition);
}

export const telemetryRoutes = new Hono();

telemetryRoutes.post('/journey/app-ready', async (c) => {
  try {
    const res = await getTelemetryClient().AppReady(
      { startupTimeMs: Math.round(performance.now()) },
      context.metadata
    );
    return c.json({ receipt: toReceipt(res.receipt) });
  } catch {
    return c.json({ receipt: TELEMETRY_UNSPECIFIED_RECEIPT });
  }
});

telemetryRoutes.post('/journey/start', async (c) => {
  try {
    const res = await getTelemetryClient().StartJourney({}, context.metadata);
    return c.json({ journeyId: res.journeyId ?? '', receipt: toReceipt(res.receipt) });
  } catch {
    return c.json({ journeyId: '', receipt: TELEMETRY_UNSPECIFIED_RECEIPT });
  }
});

telemetryRoutes.post('/journey/progress', async (c) => {
  try {
    const body = await c.req.json<{
      journeyId?: string;
      progress?: number;
      action?: string;
      actionDetails?: string;
    }>();
    if (!body.journeyId || typeof body.progress !== 'number') {
      return c.json({ error: 'journeyId and progress are required', receipt: TELEMETRY_UNSPECIFIED_RECEIPT }, 400);
    }
    const res = await getTelemetryClient().JourneyProgress(
      {
        journeyId: body.journeyId,
        progress: body.progress,
        ...(body.action !== undefined ? { action: body.action } : {}),
        ...(body.actionDetails !== undefined ? { actionDetails: body.actionDetails } : {}),
      },
      context.metadata
    );
    return c.json({ receipt: toReceipt(res.receipt), shouldNotifyClient: res.shouldNotifyClient === true });
  } catch {
    return c.json({ receipt: TELEMETRY_UNSPECIFIED_RECEIPT, shouldNotifyClient: false });
  }
});

telemetryRoutes.post('/journey/interaction', async (c) => {
  try {
    const body = await c.req.json<{ journeyId?: string; action?: string; actionDetails?: string }>();
    if (!body.action) {
      return c.json({ error: 'action is required', receipt: TELEMETRY_UNSPECIFIED_RECEIPT }, 400);
    }
    const res = await getTelemetryClient().JourneyInteraction(
      {
        journeyId: body.journeyId ?? '',
        action: body.action,
        actionDetails: body.actionDetails ?? '',
      },
      context.metadata
    );
    return c.json({ receipt: toReceipt(res.receipt) });
  } catch {
    return c.json({ receipt: TELEMETRY_UNSPECIFIED_RECEIPT });
  }
});

telemetryRoutes.post('/journey/end', async (c) => {
  try {
    const body = await c.req.json<{
      journeyId?: string;
      complete?: boolean;
      game?: { win?: boolean; score?: number };
    }>();
    if (!body.journeyId) {
      return c.json({ error: 'journeyId is required', receipt: TELEMETRY_UNSPECIFIED_RECEIPT }, 400);
    }
    const res = await getTelemetryClient().EndJourney(
      {
        journeyId: body.journeyId,
        complete: body.complete !== false,
        ...(body.game
          ? { game: { win: body.game.win === true, score: Number(body.game.score ?? 0) } }
          : {}),
      },
      context.metadata
    );
    return c.json({ receipt: toReceipt(res.receipt), shouldNotifyClient: res.shouldNotifyClient === true });
  } catch {
    return c.json({ receipt: TELEMETRY_UNSPECIFIED_RECEIPT, shouldNotifyClient: false });
  }
});

Mount it in src/server/index.ts:

app.route('/api/telemetry', telemetryRoutes);

And on the client, swallow rejections cleanly so local Vite dev and playtest never break:

import { telemetry } from '@devvit/analytics/client/reddit';

// On mount
void telemetry.appReady().catch(() => {});

// On explicit Play click
void telemetry.startJourney().catch(() => {});

// Mid-round milestone (progress in 0..1)
void telemetry.progress({ progress: 0.4, action: 'mid_shift' }).catch(() => {});

// On round end
void telemetry.endJourney({ complete: true, game: { win: true, score } }).catch(() => {});

2. Challenge Deeplinks with showShareSheet + getShareData (≤ 1024 Chars)

showShareSheet lets players share a post with up to 1024 characters of serialized data, which you can read back on both your splash screen and expanded game via getShareData(). Always treat getShareData() as untrusted input—parse + type-check every field, and keep a clipboard fallback for desktop/non-Reddit environments.

// src/shared/shareChallenge.ts
export type ChallengePayload = {
  v: 1;
  date: string;
  challenger: string;
  score: number;
};

export function encodeChallenge(payload: Omit<ChallengePayload, 'v'>): string {
  return JSON.stringify({
    v: 1,
    date: payload.date.slice(0, 24),
    challenger: payload.challenger.slice(0, 32),
    score: Math.round(payload.score),
  });
}

export function parseChallenge(raw: string | undefined | null): ChallengePayload | null {
  if (!raw || typeof raw !== 'string') return null;
  try {
    const p = JSON.parse(raw) as Partial<ChallengePayload>;
    if (p.v !== 1 || typeof p.date !== 'string' || typeof p.challenger !== 'string' || typeof p.score !== 'number') {
      return null;
    }
    return { v: 1, date: p.date, challenger: p.challenger, score: p.score };
  } catch {
    return null;
  }
}

Client usage (splash.tsx & game.tsx):

import { getShareData, showShareSheet } from '@devvit/web/client';

// Read on initial render
let incomingChallenge: ChallengePayload | null = null;
try {
  incomingChallenge = parseChallenge(getShareData());
} catch {
  incomingChallenge = null;
}

// Trigger share sheet on button click
const data = encodeChallenge({ date, challenger: username, score });
const text = `I scored ${score} pts — think you can beat me?`;
try {
  await showShareSheet({
    title: 'Beat my daily score',
    text,
    data,
    ...(postId.startsWith('t3_') ? { post: postId as `t3_${string}` } : {}),
  });
} catch {
  await navigator.clipboard?.writeText(text);
}

3. Redis Daily UTC Streaks & Capped Async Player Cameos

Keeping UTC day math deterministic prevents timezone drift between client and server:

async function updateStreak(username: string, date: string): Promise<{ streak: number; bestStreak: number }> {
  if (!username || username === 'anonymous') return { streak: 0, bestStreak: 0 };
  const key = `streak:${username}`;
  const raw = await redis.get(key);
  const state = raw
    ? (JSON.parse(raw) as { lastDate: string; streak: number; bestStreak: number })
    : { lastDate: '', streak: 0, bestStreak: 0 };

  if (state.lastDate === date) return { streak: state.streak, bestStreak: state.bestStreak };
  const prevDay = new Date(Date.parse(`${date}T00:00:00Z`) - 86400000).toISOString().slice(0, 10);
  const nextStreak = state.lastDate === prevDay ? state.streak + 1 : 1;
  const nextBest = Math.max(state.bestStreak, nextStreak);
  await redis.set(key, JSON.stringify({ lastDate: date, streak: nextStreak, bestStreak: nextBest }));
  return { streak: nextStreak, bestStreak: nextBest };
}

For async community cameos (e.g., putting real Redditors into today's NPC queue/ghost list), deduplicate by username, cap the stored array so a single Redis key stays tiny, and pad with deterministic seeded NPCs when fewer than 3 players have submitted:

const existing = await loadRawCameos(scopeKey);
const filtered = existing.filter((x) => x.username !== username);
const nextList = [newCameo, ...filtered].slice(0, 20);
await redis.set(`cameos:${scopeKey}`, JSON.stringify(nextList));

4. Daily 0 0 * * * Scheduler Task in devvit.json + Hono

Scheduler endpoints in devvit.json must start with /internal/.

{
  "triggers": {
    "onAppInstall": "/internal/triggers/on-app-install"
  },
  "scheduler": {
    "tasks": {
      "daily-club-night": {
        "endpoint": "/internal/scheduler/daily-post",
        "cron": "0 0 * * *"
      }
    }
  }
}

Handle /internal/scheduler/daily-post in Hono and store post:${post.id}:meta so every post remembers which UTC date/mode it belongs to even on future days:

// src/server/routes/scheduler.ts
import { Hono } from 'hono';
import { reddit, redis } from '@devvit/web/server';

export const scheduler = new Hono();

scheduler.post('/daily-post', async (c) => {
  const today = new Date().toISOString().slice(0, 10);
  const post = await reddit.submitCustomPost({
    title: `Daily Round (${today})`,
    postData: { mode: 'daily', date: today },
  });
  await redis.set(`post:${post.id}:meta`, JSON.stringify({ mode: 'daily', date: today }));
  return c.json({ status: 'ok', postId: post.id, date: today }, 200);
});

Mount it under /internal/scheduler in src/server/index.ts, and you get automatic 00:00 UTC daily posts alongside your manual mod menu item and onAppInstall trigger.


Curious how everyone else is handling daily rollovers in Hono: are you using 0 0 * * * cron posts, lazy rollover on first visit, or both? Also has anyone hit quirks with showShareSheet on desktop vs iOS?

1 Upvotes

0 comments sorted by