feat(remix): support serving app under a sub-path via NEXT_PUBLIC_BASE_PATH (#2824)

This commit is contained in:
Christopher Ryan
2026-08-12 16:12:28 +10:00
committed by GitHub
parent 962cffc9f5
commit 1bd09480e6
27 changed files with 189 additions and 50 deletions
+2 -1
View File
@@ -1,5 +1,6 @@
import { authClient } from '@documenso/auth/client';
import { AuthenticationErrorCode } from '@documenso/auth/server/lib/errors/error-codes';
import { formatPath } from '@documenso/lib/constants/app';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { env } from '@documenso/lib/utils/env';
import { zEmail } from '@documenso/lib/utils/zod';
@@ -44,7 +45,7 @@ const handleFallbackErrorMessages = (code: string) => {
return message;
};
const LOGIN_REDIRECT_PATH = '/';
const LOGIN_REDIRECT_PATH = formatPath('/');
export const ZSignInFormSchema = z.object({
email: zEmail().min(1),
@@ -1,5 +1,6 @@
import { useDebouncedValue } from '@documenso/lib/client-only/hooks/use-debounced-value';
import { useSession } from '@documenso/lib/client-only/providers/session';
import { formatPath } from '@documenso/lib/constants/app';
import { SUPPORTED_LANGUAGES } from '@documenso/lib/constants/i18n';
import {
DOCUMENTS_PAGE_SHORTCUT,
@@ -862,7 +863,7 @@ const PromptLanguageCommands = ({
formData.append('lang', lang);
const response = await fetch('/api/locale', {
const response = await fetch(formatPath('/api/locale'), {
method: 'post',
body: formData,
});
@@ -1,4 +1,5 @@
import { authClient } from '@documenso/auth/client';
import { formatPath } from '@documenso/lib/constants/app';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button';
import { DialogFooter } from '@documenso/ui/primitives/dialog';
@@ -34,7 +35,9 @@ export const DocumentSigningAuthAccount = ({
const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;
await authClient.signOut({
redirectPath: `/signin?returnTo=${encodeURIComponent(currentPath)}#embedded=true&email=${isDirectTemplate ? '' : email}`,
redirectPath: formatPath(
`/signin?returnTo=${encodeURIComponent(currentPath)}#embedded=true&email=${isDirectTemplate ? '' : email}`,
),
});
} catch {
setIsSigningOut(false);
@@ -1,4 +1,5 @@
import { authClient } from '@documenso/auth/client';
import { formatPath } from '@documenso/lib/constants/app';
import { Button } from '@documenso/ui/primitives/button';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { msg } from '@lingui/core/macro';
@@ -21,10 +22,10 @@ export const DocumentSigningAuthPageView = ({ email, emailHasAccount }: Document
try {
setIsSigningOut(true);
let redirectPath = '/signin';
let redirectPath = formatPath('/signin');
if (email) {
redirectPath = emailHasAccount ? `/signin#email=${email}` : `/signup#email=${email}`;
redirectPath = emailHasAccount ? formatPath(`/signin#email=${email}`) : formatPath(`/signup#email=${email}`);
}
await authClient.signOut({
+10 -7
View File
@@ -1,5 +1,6 @@
import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
import { SessionProvider } from '@documenso/lib/client-only/providers/session';
import { getBasePath } from '@documenso/lib/constants/app';
import { APP_I18N_OPTIONS, type SupportedLanguageCodes } from '@documenso/lib/constants/i18n';
import { createPublicEnv } from '@documenso/lib/utils/env';
import { extractLocaleData } from '@documenso/lib/utils/i18n';
@@ -20,7 +21,6 @@ import {
useMatches,
} from 'react-router';
import { PreventFlashOnWrongTheme, ThemeProvider, useTheme } from 'remix-themes';
import type { Route } from './+types/root';
import stylesheet from './app.css?url';
import { GenericErrorLayout } from './components/general/generic-error-layout';
@@ -68,6 +68,7 @@ export async function loader({ context, request }: Route.LoaderArgs) {
lang,
theme: getTheme(),
disableAnimations,
basePath: getBasePath(),
// Surface the per-request CSP nonce produced by `securityHeadersMiddleware` so all
// SSR-rendered <script>/<style> elements in this layout (and child
// routes that need it) can carry the matching nonce attribute.
@@ -90,10 +91,10 @@ export async function loader({ context, request }: Route.LoaderArgs) {
}
export function Layout({ children }: { children: React.ReactNode }) {
const { theme } = useLoaderData<typeof loader>() || {};
const { theme, basePath } = useLoaderData<typeof loader>() || {};
return (
<ThemeProvider specifiedTheme={theme} themeAction="/api/theme">
<ThemeProvider specifiedTheme={theme} themeAction={`${basePath ?? ''}/api/theme`}>
<LayoutContent>{children}</LayoutContent>
</ThemeProvider>
);
@@ -111,6 +112,8 @@ export function LayoutContent({ children }: { children: React.ReactNode }) {
const [theme] = useTheme();
const basePath = data.basePath ?? '';
// Recipient routes (signing pages) put `documenso-branded` on <body> so the
// <style> block from `RecipientBranding` applies to BOTH the main tree and
// any portaled content (Radix dialogs/popovers/dropdowns mount outside the
@@ -126,11 +129,11 @@ export function LayoutContent({ children }: { children: React.ReactNode }) {
<html translate="no" lang={lang} data-theme={theme} className={theme ?? ''} suppressHydrationWarning>
<head>
<meta charSet="utf-8" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="apple-touch-icon" sizes="180x180" href={`${basePath}/apple-touch-icon.png`} />
<link rel="icon" type="image/png" sizes="32x32" href={`${basePath}/favicon-32x32.png`} />
<link rel="icon" type="image/png" sizes="16x16" href={`${basePath}/favicon-16x16.png`} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="manifest" href={`${basePath}/site.webmanifest`} />
<meta name="google" content="notranslate" />
<Meta />
<Links nonce={nonce(cspNonce)} />
+3 -2
View File
@@ -5,8 +5,9 @@
*
* No translations required.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { formatPath } from '@documenso/lib/constants/app';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router';
export const loader = () => {
@@ -147,7 +148,7 @@ export default function EmbedPlaygroundPage() {
return inputToken;
}
const response = await fetch('/api/v2/embedding/create-presign-token', {
const response = await fetch(formatPath('/api/v2/embedding/create-presign-token'), {
method: 'POST',
headers: {
Authorization: `Bearer ${inputToken}`,
+2 -2
View File
@@ -3,12 +3,12 @@
"short_name": "Documenso",
"icons": [
{
"src": "/android-chrome-192x192.png",
"src": "./android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"src": "./android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
+5
View File
@@ -3,4 +3,9 @@ import type { Config } from '@react-router/dev/config';
export default {
appDirectory: 'app',
ssr: true,
// Must never be undefined and must start with the raw Vite `base` value,
// otherwise @react-router/dev crashes / exits on `react-router dev`. Both are
// kept without a trailing slash so they match exactly, and so the bare
// sub-path URL (e.g. "/ESign") still matches the basename at runtime.
basename: process.env.NEXT_PUBLIC_BASE_PATH ? process.env.NEXT_PUBLIC_BASE_PATH.replace(/\/$/, '') : '/',
} satisfies Config;
@@ -1,3 +1,4 @@
import { formatPath } from '@documenso/lib/constants/app';
import { z } from 'zod';
import { type TDetectFieldsRequest, ZNormalizedFieldWithContextSchema } from './detect-fields.types';
@@ -69,7 +70,7 @@ export const detectFields = async ({
onError,
signal,
}: DetectFieldsOptions): Promise<void> => {
const response = await fetch('/api/ai/detect-fields', {
const response = await fetch(formatPath('/api/ai/detect-fields'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -1,3 +1,4 @@
import { formatPath } from '@documenso/lib/constants/app';
import { ZDetectedRecipientSchema } from '@documenso/lib/server-only/ai/envelope/detect-recipients/schema';
import { z } from 'zod';
@@ -70,7 +71,7 @@ export const detectRecipients = async ({
onError,
signal,
}: DetectRecipientsOptions): Promise<void> => {
const response = await fetch('/api/ai/detect-recipients', {
const response = await fetch(formatPath('/api/ai/detect-recipients'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+13
View File
@@ -14,9 +14,22 @@ import { getLoadContext } from './hono/server/load-context.js';
import server from './hono/server/router.js';
import * as build from './index.js';
// Sub-path the app is served under (e.g. "/ESign"). Empty = root.
// Must match the basePath used by the Hono router and the Vite `base`/RR
// `basename` so that hashed asset URLs like `/ESign/assets/app-xxx.css`
// resolve to files on disk at `build/client/assets/app-xxx.css`.
const basePath = (process.env.NEXT_PUBLIC_BASE_PATH ?? '').replace(/\/$/, '');
server.use(
serveStatic({
root: 'build/client',
rewriteRequestPath: (path) => {
if (basePath && (path === basePath || path.startsWith(`${basePath}/`))) {
const stripped = path.slice(basePath.length);
return stripped === '' ? '/' : stripped;
}
return path;
},
onFound: (path, c) => {
if (path.startsWith('build/client/assets')) {
// Hard cache assets with hashed file names.
+3 -1
View File
@@ -46,7 +46,9 @@ export interface HonoEnv {
};
}
const app = new Hono<HonoEnv>();
const basePath = (env('NEXT_PUBLIC_BASE_PATH') ?? '').replace(/\/$/, '');
const app = new Hono<HonoEnv>().basePath(basePath || '/');
/**
* Database-backed rate limiting for API routes.
+4 -2
View File
@@ -1,4 +1,4 @@
import { API_V2_BETA_URL, API_V2_URL } from '@documenso/lib/constants/app';
import { API_V2_BETA_URL, API_V2_URL, formatPath } from '@documenso/lib/constants/app';
import { AppError, genericErrorCodeToTrpcErrorCodeMap } from '@documenso/lib/errors/app-error';
import { createTrpcContext } from '@documenso/trpc/server/context';
import { appRouter } from '@documenso/trpc/server/router';
@@ -11,8 +11,10 @@ type OpenApiTrpcServerHandlerOptions = {
};
export const openApiTrpcServerHandler = async (c: Context, { isBeta }: OpenApiTrpcServerHandlerOptions) => {
const endpoint = formatPath(isBeta ? API_V2_BETA_URL : API_V2_URL) as `/${string}`;
return createOpenApiFetchHandler<typeof appRouter>({
endpoint: isBeta ? API_V2_BETA_URL : API_V2_URL,
endpoint,
router: appRouter,
createContext: async () => createTrpcContext({ c, requestSource: 'apiV2' }),
req: c.req.raw,
+6 -1
View File
@@ -1,3 +1,4 @@
import { formatPath } from '@documenso/lib/constants/app';
import { createTrpcContext } from '@documenso/trpc/server/context';
import { appRouter } from '@documenso/trpc/server/router';
import { handleTrpcRouterError } from '@documenso/trpc/utils/trpc-error-handler';
@@ -5,10 +6,14 @@ import { trpcServer } from '@hono/trpc-server';
/**
* Trpc server for internal routes like /api/trpc/*
*
* `endpoint` must include the sub-path prefix (e.g. "/ESign") because the
* @hono/trpc-server adapter slices the prefix off the full URL pathname to
* compute the procedure name. Hono's `basePath` doesn't rewrite the URL.
*/
export const reactRouterTrpcServer = trpcServer({
router: appRouter,
endpoint: '/api/trpc',
endpoint: formatPath('/api/trpc'),
createContext: async (_, c) => createTrpcContext({ c, requestSource: 'app' }),
onError: (opts) => handleTrpcRouterError(opts, 'trpc'),
});
+4
View File
@@ -23,6 +23,10 @@ const cMapsDir = normalizePath(path.join(pdfjsDistPath, 'cmaps'));
* Do not configure any envs here.
*/
export default defineConfig({
// No trailing slash: the React Router dev server requires its `basename` to
// start with this raw value (see react-router.config.ts). Vite normalizes
// and joins asset URLs correctly either way.
base: process.env.NEXT_PUBLIC_BASE_PATH ? process.env.NEXT_PUBLIC_BASE_PATH.replace(/\/$/, '') : '/',
css: {
postcss: {
plugins: [tailwindcss, autoprefixer],