Files
Innei 12fa88e49a ✨ feat(auth): split the auth surface into a prerendered micro app (#18542)
* ♻️ refactor(auth): make the auth shell safe to prerender

Three changes, all behaviour-preserving for the current client-rendered
auth SPA, that a prerendered copy of the same pages needs:

- `enableBusinessFeatures` is a build-time constant, not deployment state.
  `AuthServerConfigProvider` now reads it from `@lobechat/business-const`
  instead of the injected server config, so a render that has not received
  that config yet still resolves the right SSO provider source.
- The terms checkbox and the "last used" provider both seeded `useState`
  from `localStorage` during render. A returning user's stored value makes
  the first render depend on the browser, which cannot be prerendered; they
  now start empty and fill in from an effect.
- `LobeAnalyticsProviderWrapper` accepts the analytics config as a prop and
  guards its `window` read, so it can render outside a browser.

Also drops the `@/features/AuthShell` barrel from the `src/features/Auth`
importers: the barrel re-exports `AuthShell`, which pulls `AuthLocale` and
the full en-US dictionary into every consumer's graph.

* ✨ feat(auth): split the auth surface into a prerendered micro app

`apps/auth` renders the sign-in flow ahead of time instead of shipping an
empty `#root`. React Router framework mode with `ssr: false` + `prerender`,
so the worker carries no React at all — 7KB, it picks one prerendered
document by locale and swaps in the deployment's config.

- 18 locales x 4 routes = 72 documents, plus a SPA fallback for the routes
  that take params. One build pass per locale writes the same canonical
  paths; the non-default passes are folded into `build/client/__i18n/`.
  Passes are independent, so they run 6 at a time (3m05s -> 44s).
- Each document inlines only its own locale's dictionary; the rest load on
  demand for the language switcher, which keeps them off the first-load
  path entirely.
- `/webapi/auth/spa-config` is a new public endpoint the worker reads to
  fill `window.__SERVER_CONFIG__`. It carries only the six fields the auth
  pages actually read; a failed lookup leaves the placeholder and the page
  still renders.
- Per-route SEO: real localized titles, and `noindex, nofollow` on every
  transactional page — only /signin and /signup stay indexable, with a
  canonical URL.

The existing Next.js `/spa-auth` route is untouched, so self-hosted and
Docker deployments keep serving the client-rendered SPA. This app builds
and deploys from lobehub-cloud, which overlays `@/business/*`.

* 🐛 fix(auth): restore feature flags and track the prerender lib
2026-09-03 19:34:41 +08:00

105 lines
3.3 KiB
TypeScript

import { resolveRequestLocale } from '@/locales/requestLocale';
import {
documentPathFor,
resolveDocumentLocale,
SPA_FALLBACK_DOCUMENT,
} from '../app/lib/prerender';
import { injectServerConfig, withDocumentLocale } from './document';
interface Env {
ASSETS: { fetch: (request: Request) => Promise<Response> };
AUTH_API_BASE?: string;
AUTH_APP_HOME?: string;
}
const API_PREFIXES = ['/api', '/oidc', '/trpc', '/webapi'];
const AUTH_PATH_PREFIXES = [
'/signin',
'/signup',
'/verify-email',
'/reset-password',
'/auth-error',
'/market-auth-callback',
'/oauth',
];
const CONFIG_ENDPOINT = '/webapi/auth/spa-config';
const matchesPrefix = (pathname: string, prefixes: string[]) =>
prefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
const isAssetPath = (pathname: string) =>
pathname.startsWith('/assets/') || pathname.slice(pathname.lastIndexOf('/')).includes('.');
const stripTrailingSlash = (pathname: string) =>
pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;
const loadServerConfig = async (env: Env, request: Request): Promise<unknown | undefined> => {
if (!env.AUTH_API_BASE) return undefined;
const target = new URL(CONFIG_ENDPOINT, env.AUTH_API_BASE);
try {
// The endpoint answers with `s-maxage`, so the edge cache handles the TTL.
const response = await fetch(target, {
headers: { accept: 'application/json', cookie: request.headers.get('cookie') ?? '' },
});
if (!response.ok) return undefined;
return await response.json();
} catch {
// A config lookup failure must not take the sign-in page down: the document
// still renders, and the browser falls back to the config-less state.
return undefined;
}
};
const serveDocument = async (request: Request, env: Env, pathname: string) => {
const locale = resolveDocumentLocale(resolveRequestLocale(request));
const url = new URL(request.url);
const documentPath = documentPathFor(pathname, locale);
const [document, serverConfig] = await Promise.all([
env.ASSETS.fetch(new Request(new URL(documentPath, url.origin), { headers: request.headers })),
loadServerConfig(env, request),
]);
if (!document.ok) return document;
let html = injectServerConfig(await document.text(), serverConfig);
if (documentPath === SPA_FALLBACK_DOCUMENT) html = withDocumentLocale(html, locale);
return new Response(html, {
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'text/html; charset=utf-8',
},
});
};
export default {
fetch(request: Request, env: Env) {
const url = new URL(request.url);
const pathname = stripTrailingSlash(url.pathname);
// Standalone deployments have no reverse proxy in front: forward the app's
// same-origin API calls to the backend, mirroring vite's dev proxy.
if (env.AUTH_API_BASE && matchesPrefix(pathname, API_PREFIXES)) {
const target = new URL(url.pathname + url.search, env.AUTH_API_BASE);
return fetch(new Request(target, request));
}
if (isAssetPath(pathname)) return env.ASSETS.fetch(request);
if (!matchesPrefix(pathname, AUTH_PATH_PREFIXES))
return Response.redirect(env.AUTH_APP_HOME || 'https://lobehub.com', 302);
return serveDocument(request, env, pathname);
},
};