diff --git a/backend/package.json b/backend/package.json
index b8a4365..9e546ac 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -1,6 +1,6 @@
{
"name": "backend",
- "version": "1.12.1",
+ "version": "1.12.2",
"private": true,
"type": "commonjs",
"main": "src/index.js",
@@ -20,6 +20,7 @@
"@prisma/adapter-pg": "^7.10.0",
"@prisma/client": "^7.10.0",
"bcrypt": "^6.0.0",
+ "compression": "^1.8.2",
"cors": "^2.8.5",
"dotenv": "^18.0.6",
"express": "^5.2.1",
diff --git a/backend/prisma/migrations/20261009150000_foreign_key_indexes/migration.sql b/backend/prisma/migrations/20261009150000_foreign_key_indexes/migration.sql
new file mode 100644
index 0000000..71d327b
--- /dev/null
+++ b/backend/prisma/migrations/20261009150000_foreign_key_indexes/migration.sql
@@ -0,0 +1,20 @@
+-- CreateIndex: the columns every list is looked up by. Postgres does not
+-- index a foreign key on its own.
+CREATE INDEX "locations_campaignId_idx" ON "locations"("campaignId");
+CREATE INDEX "campaign_members_userId_idx" ON "campaign_members"("userId");
+CREATE INDEX "characters_campaignId_idx" ON "characters"("campaignId");
+CREATE INDEX "characters_userId_idx" ON "characters"("userId");
+CREATE INDEX "weapons_campaignId_idx" ON "weapons"("campaignId");
+CREATE INDEX "items_campaignId_idx" ON "items"("campaignId");
+CREATE INDEX "spells_campaignId_idx" ON "spells"("campaignId");
+CREATE INDEX "monsters_campaignId_idx" ON "monsters"("campaignId");
+CREATE INDEX "npcs_campaignId_idx" ON "npcs"("campaignId");
+CREATE INDEX "encounters_campaignId_idx" ON "encounters"("campaignId");
+CREATE INDEX "encounter_rewards_encounterId_idx" ON "encounter_rewards"("encounterId");
+CREATE INDEX "sale_offers_campaignId_idx" ON "sale_offers"("campaignId");
+CREATE INDEX "sale_offers_npcId_idx" ON "sale_offers"("npcId");
+CREATE INDEX "sale_offers_encounterId_idx" ON "sale_offers"("encounterId");
+CREATE INDEX "encounter_participants_encounterId_idx" ON "encounter_participants"("encounterId");
+CREATE INDEX "encounter_participants_characterId_idx" ON "encounter_participants"("characterId");
+CREATE INDEX "notes_campaignId_idx" ON "notes"("campaignId");
+CREATE INDEX "notes_characterId_idx" ON "notes"("characterId");
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index dc4a90b..6ca9b67 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -213,6 +213,7 @@ model Location {
encounters Encounter[]
visits CharacterLocationVisit[]
+ @@index([campaignId])
@@map("locations")
}
@@ -243,6 +244,7 @@ model CampaignMember {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([campaignId, userId])
+ @@index([userId])
@@map("campaign_members")
}
@@ -323,6 +325,8 @@ model Character {
encounterEntries EncounterParticipant[]
locationVisits CharacterLocationVisit[]
+ @@index([campaignId])
+ @@index([userId])
@@map("characters")
}
@@ -386,6 +390,7 @@ model Weapon {
rewards EncounterReward[]
offers SaleOffer[]
+ @@index([campaignId])
@@map("weapons")
}
@@ -425,6 +430,7 @@ model Item {
rewards EncounterReward[]
offers SaleOffer[]
+ @@index([campaignId])
@@map("items")
}
@@ -486,6 +492,7 @@ model Spell {
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
known CharacterSpell[]
+ @@index([campaignId])
@@map("spells")
}
@@ -528,6 +535,7 @@ model Monster {
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
encounterAppearances EncounterParticipant[]
+ @@index([campaignId])
@@map("monsters")
}
@@ -555,6 +563,7 @@ model Npc {
encounterAppearances EncounterParticipant[]
wares SaleOffer[]
+ @@index([campaignId])
@@map("npcs")
}
@@ -590,6 +599,7 @@ model Encounter {
rewards EncounterReward[]
wares SaleOffer[]
+ @@index([campaignId])
@@map("encounters")
}
@@ -615,6 +625,7 @@ model EncounterReward {
weapon Weapon? @relation(fields: [weaponId], references: [id], onDelete: Cascade)
item Item? @relation(fields: [itemId], references: [id], onDelete: Cascade)
+ @@index([encounterId])
@@map("encounter_rewards")
}
@@ -642,6 +653,9 @@ model SaleOffer {
weapon Weapon? @relation(fields: [weaponId], references: [id], onDelete: Cascade)
item Item? @relation(fields: [itemId], references: [id], onDelete: Cascade)
+ @@index([campaignId])
+ @@index([npcId])
+ @@index([encounterId])
@@map("sale_offers")
}
@@ -672,6 +686,8 @@ model EncounterParticipant {
monster Monster? @relation(fields: [monsterId], references: [id], onDelete: SetNull)
npc Npc? @relation(fields: [npcId], references: [id], onDelete: SetNull)
+ @@index([encounterId])
+ @@index([characterId])
@@map("encounter_participants")
}
@@ -692,5 +708,7 @@ model Note {
character Character? @relation(fields: [characterId], references: [id], onDelete: Cascade)
author User @relation(fields: [authorId], references: [id])
+ @@index([campaignId])
+ @@index([characterId])
@@map("notes")
}
diff --git a/backend/src/app.js b/backend/src/app.js
index 99e213b..87aa6eb 100644
--- a/backend/src/app.js
+++ b/backend/src/app.js
@@ -1,5 +1,6 @@
const express = require('express');
const cors = require('cors');
+const compression = require('compression');
const authRoutes = require('./routes/auth.routes');
const campaignsRoutes = require('./routes/campaigns.routes');
@@ -11,6 +12,9 @@ function createApp() {
const app = express();
app.use(cors({ origin: process.env.CORS_ORIGIN || 'http://localhost:5173' }));
+ // Nothing in front of the API compresses for it (frp only tunnels), so the
+ // JSON is gzipped here.
+ app.use(compression());
app.use(express.json());
app.get('/health', (req, res) => res.json({ ok: true }));
diff --git a/backend/src/middleware/campaignAccess.js b/backend/src/middleware/campaignAccess.js
index 61d8e21..85f9c4f 100644
--- a/backend/src/middleware/campaignAccess.js
+++ b/backend/src/middleware/campaignAccess.js
@@ -12,11 +12,18 @@ function requireCampaignMember() {
return async (req, res, next) => {
const campaignId = req.params.campaignId || req.params.id;
try {
- const campaign = await prisma.campaign.findUnique({ where: { id: campaignId } });
- if (!campaign) return res.status(404).json({ error: 'Campaign not found' });
-
- const membership = await loadCampaignMembership(req.user.id, campaignId);
- if (!membership) return res.status(403).json({ error: 'Not a member of this campaign' });
+ // One query for a member, which is nearly every request. Only when it
+ // finds nothing is the campaign looked up, to tell a 404 from a 403.
+ const found = await prisma.campaignMember.findUnique({
+ where: { campaignId_userId: { campaignId, userId: req.user.id } },
+ include: { campaign: true },
+ });
+ if (!found) {
+ const exists = await prisma.campaign.findUnique({ where: { id: campaignId }, select: { id: true } });
+ if (!exists) return res.status(404).json({ error: 'Campaign not found' });
+ return res.status(403).json({ error: 'Not a member of this campaign' });
+ }
+ const { campaign, ...membership } = found;
req.campaign = campaign;
req.membership = membership;
diff --git a/backend/src/routes/api.integration.test.js b/backend/src/routes/api.integration.test.js
index 44ef92d..cb87296 100644
--- a/backend/src/routes/api.integration.test.js
+++ b/backend/src/routes/api.integration.test.js
@@ -1442,6 +1442,7 @@ describe('default content library', () => {
expect((await request(app).get(`/campaigns/${campaign.id}/library`).set(playerAuth)).status).toBe(403);
const listRes = await request(app).get(`/campaigns/${campaign.id}/library`).set(dmAuth);
expect(listRes.status).toBe(200);
+ expect(listRes.headers['content-encoding']).toBe('gzip'); // a big answer goes out compressed
expect(listRes.body.weapons.length).toBeGreaterThan(20);
expect(listRes.body.spells.length).toBeGreaterThan(50);
expect(listRes.body.monsters.length).toBeGreaterThan(20);
diff --git a/frontend/package.json b/frontend/package.json
index c1d26f3..10e6f5a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
- "version": "1.12.1",
+ "version": "1.12.2",
"type": "module",
"scripts": {
"dev": "vite",
@@ -18,10 +18,12 @@
"socket.io-client": "^4.8.3"
},
"devDependencies": {
+ "@types/compression": "^1.8.1",
"@types/node": "^24.13.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
+ "compression": "^1.8.2",
"oxlint": "^1.81.0",
"typescript": "~7.0.2",
"vite": "^8.3.0"
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index afd9aa3..0c12173 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,35 +1,41 @@
+import { lazy, Suspense } from 'react';
import { Navigate, Route, Routes } from 'react-router-dom';
import { Layout } from './components/Layout';
import { ProtectedRoute } from './components/ProtectedRoute';
import { LoginPage } from './pages/LoginPage';
-import { RegisterPage } from './pages/RegisterPage';
-import { CampaignListPage } from './pages/CampaignListPage';
-import { CampaignHomePage } from './pages/CampaignHomePage';
-import { PartyOverviewPage } from './pages/PartyOverviewPage';
-import { CharacterSheetPage } from './pages/CharacterSheetPage';
-import { CharacterBuilderPage } from './pages/CharacterBuilderPage';
-import { EncounterPage } from './pages/EncounterPage';
-import { AccountPage } from './pages/AccountPage';
+
+// Each page is its own file to download, fetched the first time it is opened,
+// so signing in does not wait on the encounter tracker or the character builder.
+const RegisterPage = lazy(() => import('./pages/RegisterPage').then((m) => ({ default: m.RegisterPage })));
+const CampaignListPage = lazy(() => import('./pages/CampaignListPage').then((m) => ({ default: m.CampaignListPage })));
+const CampaignHomePage = lazy(() => import('./pages/CampaignHomePage').then((m) => ({ default: m.CampaignHomePage })));
+const PartyOverviewPage = lazy(() => import('./pages/PartyOverviewPage').then((m) => ({ default: m.PartyOverviewPage })));
+const CharacterSheetPage = lazy(() => import('./pages/CharacterSheetPage').then((m) => ({ default: m.CharacterSheetPage })));
+const CharacterBuilderPage = lazy(() => import('./pages/CharacterBuilderPage').then((m) => ({ default: m.CharacterBuilderPage })));
+const EncounterPage = lazy(() => import('./pages/EncounterPage').then((m) => ({ default: m.EncounterPage })));
+const AccountPage = lazy(() => import('./pages/AccountPage').then((m) => ({ default: m.AccountPage })));
function App() {
return (
-
- } />
- } />
- }>
- }>
- } />
- } />
- } />
- } />
- } />
- } />
- } />
- } />
+
+
+ } />
+ } />
+ }>
+ }>
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+
-
- } />
-
+ } />
+
+
);
}
diff --git a/frontend/src/api/queries.ts b/frontend/src/api/queries.ts
index 34fbb95..41e9df6 100644
--- a/frontend/src/api/queries.ts
+++ b/frontend/src/api/queries.ts
@@ -735,12 +735,21 @@ export function useEncounter(encounterId: string | undefined) {
});
}
+// Every change to an encounter is answered with the encounter as this viewer
+// sees it, so the cache takes that as it is: no second request for what just
+// came back.
+function keepEncounter(qc: QueryClient, encounterId: string, data: unknown) {
+ const encounter = (data as { encounter?: Encounter } | undefined)?.encounter;
+ if (encounter) qc.setQueryData(['encounter', encounterId], encounter);
+ else qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
+}
+
export function useAddParticipant(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: { characterId?: string; monsterId?: string; npcId?: string; displayName?: string; initiativeRoll?: number }) =>
(await apiClient.post(`/encounters/${encounterId}/participants`, data)).data,
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
@@ -749,7 +758,7 @@ export function usePatchParticipant(encounterId: string) {
return useMutation({
mutationFn: async ({ participantId, ...data }: Partial & { participantId: string }) =>
(await apiClient.patch(`/encounters/${encounterId}/participants/${participantId}`, data)).data,
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
@@ -757,8 +766,8 @@ export function useRemoveParticipant(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (participantId: string) =>
- apiClient.delete(`/encounters/${encounterId}/participants/${participantId}`),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ (await apiClient.delete(`/encounters/${encounterId}/participants/${participantId}`)).data,
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
@@ -766,7 +775,7 @@ export function useAdvanceRound(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => (await apiClient.post(`/encounters/${encounterId}/advance-round`)).data,
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
@@ -781,8 +790,8 @@ export function usePatchEncounter(encounterId: string) {
dmNotes?: string | null;
locationId?: string | null;
}) => (await apiClient.patch(`/encounters/${encounterId}`, data)).data,
- onSuccess: (_data, variables) => {
- qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
+ onSuccess: (data, variables) => {
+ keepEncounter(qc, encounterId, data);
// The campaign page lists encounters by name, mode and status, and an
// encounter in progress carries its characters to its location.
if (variables.status || variables.mode || variables.name || variables.locationId !== undefined) {
@@ -800,7 +809,7 @@ export function useSetTargets(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (participantIds: string[]) => (await apiClient.put(`/encounters/${encounterId}/targets`, { participantIds })).data,
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
@@ -810,8 +819,8 @@ export function useReviveParticipant(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (participantId: string) => (await apiClient.post(`/encounters/${encounterId}/participants/${participantId}/revive`)).data,
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
+ onSuccess: (data) => {
+ keepEncounter(qc, encounterId, data);
qc.invalidateQueries({ queryKey: ['character'] }); // the revived character's sheet
},
});
@@ -821,7 +830,7 @@ export function useNextTurn(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => (await apiClient.post(`/encounters/${encounterId}/next-turn`)).data,
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
@@ -838,15 +847,15 @@ export function useAddReward(encounterId: string) {
const qc = useQueryClient();
return useMutation({
mutationFn: async (data: NewReward) => (await apiClient.post(`/encounters/${encounterId}/rewards`, data)).data,
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
export function useDeleteReward(encounterId: string) {
const qc = useQueryClient();
return useMutation({
- mutationFn: async (rewardId: string) => apiClient.delete(`/encounters/${encounterId}/rewards/${rewardId}`),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['encounter', encounterId] }),
+ mutationFn: async (rewardId: string) => (await apiClient.delete(`/encounters/${encounterId}/rewards/${rewardId}`)).data,
+ onSuccess: (data) => keepEncounter(qc, encounterId, data),
});
}
@@ -857,8 +866,8 @@ export function useAwardReward(encounterId: string) {
return useMutation({
mutationFn: async ({ rewardId, ...target }: { rewardId: string } & ({ characterId: string } | { split: true })) =>
(await apiClient.post(`/encounters/${encounterId}/rewards/${rewardId}/award`, target)).data,
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
+ onSuccess: (data) => {
+ keepEncounter(qc, encounterId, data);
qc.invalidateQueries({ queryKey: ['character'] });
qc.invalidateQueries({ queryKey: ['campaign'] });
},
@@ -927,8 +936,8 @@ export function useDeleteWare(campaignId: string) {
}
// Both change what a character holds, so the sheet and the party list refresh too.
-function invalidateAfterTrade(qc: QueryClient, encounterId: string) {
- qc.invalidateQueries({ queryKey: ['encounter', encounterId] });
+function invalidateAfterTrade(qc: QueryClient, encounterId: string, data: unknown) {
+ keepEncounter(qc, encounterId, data);
qc.invalidateQueries({ queryKey: ['character'] });
qc.invalidateQueries({ queryKey: ['campaign'] });
}
@@ -939,7 +948,7 @@ export function useExchangeWithNpc(encounterId: string) {
return useMutation({
mutationFn: async (data: { characterId: string; npcId: string; from: 'GOLD' | 'CASH'; amount: number }) =>
(await apiClient.post<{ received: number; currency: Currency }>(`/encounters/${encounterId}/exchange`, data)).data,
- onSuccess: () => invalidateAfterTrade(qc, encounterId),
+ onSuccess: (data) => invalidateAfterTrade(qc, encounterId, data),
});
}
@@ -948,7 +957,7 @@ export function useBuyWare(encounterId: string) {
return useMutation({
mutationFn: async ({ wareId, ...data }: { wareId: string; characterId: string; quantity?: number }) =>
(await apiClient.post(`/encounters/${encounterId}/wares/${wareId}/buy`, data)).data,
- onSuccess: () => invalidateAfterTrade(qc, encounterId),
+ onSuccess: (data) => invalidateAfterTrade(qc, encounterId, data),
});
}
diff --git a/frontend/src/components/Layout.tsx b/frontend/src/components/Layout.tsx
index 3c80b8a..420b0a1 100644
--- a/frontend/src/components/Layout.tsx
+++ b/frontend/src/components/Layout.tsx
@@ -1,3 +1,4 @@
+import { Suspense } from 'react';
import { Link, NavLink, Outlet, useMatch } from 'react-router-dom';
import { useAuth } from '../auth/useAuth';
import { useLastCampaignId, useRememberCampaign } from '../lib/lastCampaign';
@@ -57,7 +58,10 @@ export function Layout() {
)}
-
+ {/* The bars stay put while a page that has not been opened before downloads. */}
+
+
+
{user && (