Fix: Base path resolution timing issue for subpath deployments (#572)

When deployed under a URL prefix (e.g., /shelfmark), images loaded by
React were not respecting the base path, causing 404 errors. The logo
would incorrectly load from /logo.png instead of /shelfmark/logo.png.

The root cause was that the BASE_PATH constant was being initialized at
module load time, before the DOM was fully parsed. This meant
document.querySelector('base') returned null, causing BASE_PATH to
default to '/' regardless of the actual base tag value.

Changed to lazy initialization pattern where the base path is resolved
on first access, ensuring the DOM and base tag are ready.

Fixes [#571](https://github.com/calibrain/shelfmark/issues/571)
This commit is contained in:
Andy Kelk
2026-02-02 17:26:06 +00:00
committed by GitHub
parent e5ccabe1ef
commit f6dba959c9
+11 -4
View File
@@ -30,16 +30,23 @@ const resolveBasePath = (): string => {
}
};
const BASE_PATH = normalizeBasePath(resolveBasePath());
// Lazy initialization to ensure DOM is ready when base path is resolved
let _basePath: string | null = null;
export const getBasePath = (): string => BASE_PATH;
export const getBasePath = (): string => {
if (_basePath === null) {
_basePath = normalizeBasePath(resolveBasePath());
}
return _basePath;
};
export const withBasePath = (path: string): string => {
const basePath = getBasePath();
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
if (BASE_PATH === '/') {
if (basePath === '/') {
return normalizedPath;
}
return `${BASE_PATH}${normalizedPath}`;
return `${basePath}${normalizedPath}`;
};
export const getApiBase = (): string => withBasePath('/api');