Skip to content

Open-source status page, incident response and uptime monitoring

chore: stpg proxy (#1365)

Maximilian Kaske577b11ec3478
diff --git a/apps/status-page/next.config.ts b/apps/status-page/next.config.ts
index a453fa85d..d99e79a9e 100644
--- a/apps/status-page/next.config.ts
+++ b/apps/status-page/next.config.ts
@@ -28,6 +28,12 @@ const nextConfig: NextConfig = {
},
],
missing: [
+ // Skip this rewrite when the request came via proxy from web app
+ {
+ type: "header",
+ key: "x-proxy",
+ value: "1",
+ },
{
type: "host",
value:
diff --git a/apps/status-page/src/middleware.ts b/apps/status-page/src/middleware.ts
index caed2df2d..ec5d8ebd8 100644
--- a/apps/status-page/src/middleware.ts
+++ b/apps/status-page/src/middleware.ts
@@ -8,11 +8,13 @@ export default async function middleware(req: NextRequest) {
const url = req.nextUrl.clone();
const response = NextResponse.next();
const cookies = req.cookies;
+ const headers = req.headers;
+ const host = headers.get("x-forwarded-host");
let prefix = "";
let type: "hostname" | "pathname";
- const hostnames = url.host.split(".");
+ const hostnames = host?.split(/[.:]/) ?? url.host.split(/[.:]/);
const pathnames = url.pathname.split("/");
if (
hostnames.length > 2 &&
@@ -33,7 +35,9 @@ export default async function middleware(req: NextRequest) {
const _page = await db.select().from(page).where(eq(page.slug, prefix)).get();
if (!_page) {
- return NextResponse.redirect(new URL("https://stpg.dev"));
+ // return NextResponse.redirect(new URL("https://stpg.dev"));
+ // TODO: work on 404 page
+ return response;
}
if (_page?.passwordProtected) {
@@ -59,6 +63,11 @@ export default async function middleware(req: NextRequest) {
}
}
+ const proxy = req.headers.get("x-proxy");
+ if (proxy) {
+ return NextResponse.rewrite(new URL(`/${prefix}${url.pathname}`, req.url));
+ }
+
return response;
}
diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts
index 3cd7048ed..1b3be0840 100644
--- a/apps/web/next-env.d.ts
+++ b/apps/web/next-env.d.ts
@@ -1,6 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-/// <reference types="next/navigation-types/compat/navigation" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/apps/web/next.config.js b/apps/web/next.config.js
index 6f39d656e..a8951d503 100644
--- a/apps/web/next.config.js
+++ b/apps/web/next.config.js
@@ -65,8 +65,11 @@ const nextConfig = {
];
},
async rewrites() {
+ const NEW_HOST =
+ process.env.NODE_ENV === "development" ? "localhost:3001" : "stpg.dev";
return {
beforeFiles: [
+ // Proxy app subdomain to /app
{
source: "/:path*",
has: [
@@ -77,6 +80,25 @@ const nextConfig = {
],
destination: "/app/:path*",
},
+ // New design: proxy Next.js assets from external host when cookie indicates "new"
+ {
+ source: "/_next/:path*",
+ has: [
+ { type: "cookie", key: "sp_mode", value: "new" },
+ { type: "host", value: "(?<slug>[^.]+)\\.(stpg\\.dev|localhost)" },
+ ],
+ destination: `http://${NEW_HOST}/_next/:path*`,
+ },
+ // New design: proxy app routes to external host with slug prefix
+ {
+ source: "/:path((?!_next/).*)",
+ has: [
+ { type: "cookie", key: "sp_mode", value: "new" },
+ { type: "host", value: "(?<slug>[^.]+)\\.(stpg\\.dev|localhost)" },
+ ],
+ // NOTE: we don't need the slug `/:slug/:path*` here because it will already be applied in the rewrites in the status-page app as subdomain
+ destination: `http://${NEW_HOST}/:path*`,
+ },
],
};
},
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
index eed5a8d2d..ac45c03a6 100644
--- a/apps/web/src/middleware.ts
+++ b/apps/web/src/middleware.ts
@@ -6,8 +6,11 @@ import { getCurrency } from "@openstatus/db/src/schema/plan/utils";
import { auth } from "@/lib/auth";
import { eq } from "@openstatus/db";
+import { Redis } from "@openstatus/upstash";
import { env } from "./env";
+const MAX_AGE = 60 * 10; // 10 minutes
+
export const getValidSubdomain = (host?: string | null) => {
let subdomain: string | null = null;
if (!host && typeof window !== "undefined") {
@@ -58,15 +61,47 @@ export default auth(async (req) => {
}
const host = req.headers.get("host");
+ const pathname = req.nextUrl.pathname;
const subdomain = getValidSubdomain(host);
- // Rewriting to status page!
+ // Subdomain handling: set mode cookie (legacy/new) and let next.config rewrites proxy
if (subdomain) {
- url.pathname = `/status-page/${subdomain}${url.pathname}`;
- return NextResponse.rewrite(url);
- }
+ const modeCookie = req.cookies.get("sp_mode")?.value; // "legacy" | "new"
+ const cached = modeCookie === "legacy" || modeCookie === "new";
+ let mode: "legacy" | "new" | undefined = cached ? modeCookie : undefined;
+
+ if (!mode) {
+ try {
+ const redis = Redis.fromEnv();
+ const cache = await redis.get(`page:${subdomain}`);
+ // Determine legacy flag from cache
+ mode = cache ? "new" : "legacy";
+ } catch {
+ mode = "legacy";
+ }
+ }
- const pathname = req.nextUrl.pathname;
+ if (mode === "legacy") {
+ url.pathname = `/status-page/${subdomain}${url.pathname}`;
+ return NextResponse.rewrite(url);
+ }
+
+ const res = NextResponse.next();
+ // Mark that this request is being proxied so downstream can adapt
+ res.headers.set("x-proxy", "1");
+ // Short-lived cookie so toggles apply relatively quickly
+ res.cookies.set("sp_mode", "new", { path: "/", maxAge: MAX_AGE });
+
+ // If we just set the cookie, trigger one redirect so next.config.js
+ // rewrites that depend on sp_mode can apply on the next request.
+ if (!cached) {
+ const redirect = NextResponse.redirect(url);
+ redirect.cookies.set("sp_mode", "new", { path: "/", maxAge: MAX_AGE });
+ return redirect;
+ }
+
+ return res;
+ }
const isPublicAppPath = publicAppPaths.some((path) =>
pathname.startsWith(path),
diff --git a/packages/api/.env.test b/packages/api/.env.test
index 6491cb9ee..2a893ecef 100644
--- a/packages/api/.env.test
+++ b/packages/api/.env.test
@@ -1,3 +1,5 @@
RESEND_API_KEY='test'
NEXT_PUBLIC_OPENPANEL_CLIENT_ID='test'
-OPENPANEL_CLIENT_SECRET='test'
\ No newline at end of file
+OPENPANEL_CLIENT_SECRET='test'
+UPSTASH_REDIS_REST_URL="test"
+UPSTASH_REDIS_REST_TOKEN="test"
\ No newline at end of file
diff --git a/packages/api/package.json b/packages/api/package.json
index 3b4d45fc9..2c1ad8f41 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -13,6 +13,7 @@
"@openstatus/emails": "workspace:*",
"@openstatus/error": "workspace:*",
"@openstatus/utils": "workspace:*",
+ "@openstatus/upstash": "workspace:*",
"@openstatus/tinybird": "workspace:*",
"@t3-oss/env-core": "0.7.1",
"@trpc/client": "11.4.4",
diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.ts
index 04dda413f..c424917dc 100644
--- a/packages/api/src/router/page.ts
+++ b/packages/api/src/router/page.ts
@@ -30,9 +30,16 @@ import {
} from "@openstatus/db/src/schema";
import { Events } from "@openstatus/analytics";
+import { Redis } from "@openstatus/upstash";
import { env } from "../env";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
+if (process.env.NODE_ENV === "test") {
+ require("../test/preload");
+}
+
+const redis = Redis.fromEnv();
+
// Helper functions to reuse Vercel API logic
async function addDomainToVercel(domain: string) {
const data = await fetch(
@@ -775,6 +782,17 @@ export const pageRouter = createTRPCRouter({
eq(page.id, opts.input.id),
];
+ const _page = await opts.ctx.db.query.page.findFirst({
+ where: and(...whereConditions),
+ });
+
+ if (!_page) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Page not found",
+ });
+ }
+
await opts.ctx.db
.update(page)
.set({
@@ -786,6 +804,18 @@ export const pageRouter = createTRPCRouter({
})
.where(and(...whereConditions))
.run();
+
+ if (opts.input.legacyPage) {
+ await redis.del(`page:${_page.slug}`);
+ if (_page.customDomain) {
+ await redis.del(`page:${_page.customDomain}`);
+ }
+ } else {
+ await redis.set(`page:${_page.slug}`, 1);
+ if (_page.customDomain) {
+ await redis.set(`page:${_page.customDomain}`, 1);
+ }
+ }
}),
updateMonitors: protectedProcedure
diff --git a/packages/api/src/test/preload.ts b/packages/api/src/test/preload.ts
new file mode 100644
index 000000000..4d43b6ffd
--- /dev/null
+++ b/packages/api/src/test/preload.ts
@@ -0,0 +1,12 @@
+import { mock } from "bun:test";
+
+mock.module("@openstatus/upstash", () => ({
+ Redis: {
+ fromEnv() {
+ return {
+ get: () => Promise.resolve(undefined),
+ set: () => Promise.resolve([]),
+ };
+ },
+ },
+}));
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3036ba4d6..78a858598 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1168,6 +1168,9 @@ importers:
'@openstatus/tinybird':
specifier: workspace:*
version: link:../tinybird
+ '@openstatus/upstash':
+ specifier: workspace:*
+ version: link:../upstash
'@openstatus/utils':
specifier: workspace:*
version: link:../utils