diff react_games/backend/routes/web.ts @ 37:fb9bcd3145cb

[ReactGames] Few games I made using react just to practice few things.
author MrJuneJune <me@mrjunejune.com>
date Mon, 01 Dec 2025 20:22:47 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/react_games/backend/routes/web.ts	Mon Dec 01 20:22:47 2025 -0800
@@ -0,0 +1,37 @@
+import { Router, static as serveStatic } from 'express';
+import path from 'node:path';
+
+type SpaMount = {
+  baseUrl: string; // Base path like /games
+  entryHtml: string; // we need to define its entry index html
+};
+
+export function createWebRouter(publicDir: string, spaMounts: SpaMount[]) {
+  const router = Router();
+
+  // order matters so geting just public one first 
+  router.use(serveStatic(publicDir, {
+    index: 'index.html',
+    extensions: ['html'],
+    setHeaders: (res) => {
+      res.setHeader('X-Content-Type-Options', 'nosniff');
+    },
+  }));
+
+  for (const { baseUrl, entryHtml } of spaMounts) {
+    router.get(baseUrl, (_req, res) => {
+      res.sendFile(path.join(publicDir, entryHtml));
+    });
+    router.get(`${baseUrl}/:rest`, (_req, res) => {
+      res.sendFile(path.join(publicDir, entryHtml));
+    });
+  }
+
+
+  router.use((_req, res) => {
+    res.status(404).send('Not Found');
+  });
+
+  return router;
+}
+