Files
SRCmail/lib/browser-navigation.ts
T
shukiandLinus Rath a7db3883aa feat: apiFetch helper for mount-prefix-aware API calls
Makes every client-side fetch('/api/...') call respect the mount prefix
when Bulwark is served behind a reverse proxy at a sub-path (e.g.
`/webmail`).

### Problem

`getPathPrefix()` (added in 1.4.13 by #XXX / d762b94) already fixes
router navigation and redirect URIs for reverse-proxy deployments.
Client-side `fetch()` calls, though, still target the browser origin:

    await fetch('/api/foo')
    // Browser at /webmail/en/inbox → hits /api/foo (not proxied → 404)

That means the login flow, session establishment, settings save, plugin
loader, calendar import, etc. all break the moment you front Bulwark
with nginx (or any proxy) at a sub-path.

### Fix

Add `apiFetch(input, init)` next to `getPathPrefix()` in
`lib/browser-navigation.ts`. It prepends the mount prefix to any
absolute path at call time:

    await apiFetch('/api/foo')
    // /webmail/en/inbox → /webmail/api/foo
    // /en/inbox         → /api/foo

Same runtime-detection model as `getPathPrefix()` — the built bundle
works at any mount point without rebuilding or env-var config.
Protocol-relative (`//cdn...`) and absolute (`https://...`) URLs pass
through unchanged. Server-side route handlers are untouched (the mount
prefix is a browser-only concept).

### Migration

Mechanical rewrite of every client-side `fetch('/api/...')` call in
hooks/, lib/, stores/, components/, app/ — 99 call sites across
26 files. `route.ts` handlers and other server-only files are skipped.

### Compat

- No behaviour change when mounted at `/` (the common case): an empty
  prefix + raw path is identical to raw path.
- No new config knobs, env vars, or build flags.
- Supersedes PR #181 (which required a build-time `NEXT_PUBLIC_BASE_PATH`)
  — will close #181 after this lands.

### Testing

Should run the existing suite; smoke-tested by Jabali Panel which
reverse-proxies Bulwark at `/webmail/` (https://github.com/shukiv/jabali-panel).
2026-04-14 14:37:19 +02:00

80 lines
2.6 KiB
TypeScript

import { locales } from '@/i18n/routing';
export function replaceWindowLocation(url: string): void {
if (typeof window === 'undefined') {
return;
}
window.location.replace(url);
}
/**
* Returns the mount prefix from the current URL.
* When the app is served behind a reverse proxy at e.g. /bulwark,
* the browser sees /bulwark/en/login while Next.js sees /en/login.
*
* If a locale is supplied (e.g. from route params) it is used directly;
* otherwise the first path segment that matches a known locale is used.
*
* Returns '' when there is no prefix.
*/
export function getPathPrefix(locale?: string): string {
if (typeof window === 'undefined') return '';
const segments = window.location.pathname.split('/').filter(Boolean);
let localeIndex: number;
if (locale) {
localeIndex = segments.indexOf(locale);
} else {
localeIndex = segments.findIndex(s =>
(locales as readonly string[]).includes(s)
);
}
if (localeIndex <= 0) return '';
return '/' + segments.slice(0, localeIndex).join('/');
}
/**
* Mount-prefix-aware wrapper around `fetch()`.
*
* When Bulwark is served behind a reverse proxy at a sub-path (e.g. `/bulwark`),
* `fetch('/api/foo')` would target the browser origin at `/api/foo`, which the
* proxy doesn't route. `apiFetch` detects the mount prefix from
* `window.location.pathname` via `getPathPrefix()` at call time, so the same
* built bundle works at any mount point without rebuilding.
*
* Only rewrites absolute paths that start with a single `/`. Protocol-relative
* URLs (`//cdn.example.com/foo`) and absolute URLs (`https://...`) pass
* through unchanged.
*
* Server code (route handlers, layout files running at SSR) should keep using
* the raw Fetch API — the mount prefix is a browser-only concept.
*
* @example
* await apiFetch('/api/jmap', { method: 'POST', body })
* // Browser at /webmail/en/inbox → /webmail/api/jmap
* // Browser at /en/inbox → /api/jmap
*/
export function apiFetch(input: string, init?: RequestInit): Promise<Response> {
if (input.startsWith('/') && !input.startsWith('//')) {
return fetch(getPathPrefix() + input, init);
}
return fetch(input, init);
}
/**
* Extracts the locale from the current URL, skipping any mount prefix.
* Falls back to 'en' when no known locale segment is found.
*/
export function getLocaleFromPath(): string {
if (typeof window === 'undefined') return 'en';
const segments = window.location.pathname.split('/').filter(Boolean);
const locale = segments.find(s =>
(locales as readonly string[]).includes(s)
);
return locale || 'en';
}