fix(auth): resolve relative directus URL against window origin

The runtime config supports relative paths like /api so the SPA can run
same-origin in dev (Vite proxy) and stage/prod (Traefik). createDirectus
from @directus/sdk calls new URL(...) internally, which throws on
relative URLs. Resolve in toAbsoluteUrl() before handing to the SDK:

  '/api' -> 'http://localhost:5173/api' (dev)
  'https://api.example.com' -> passes through unchanged

Caught at runtime; typecheck/build don't surface this since the SDK
treats its url arg as a string.
This commit is contained in:
2026-05-02 17:50:13 +02:00
parent 3917119446
commit a65ad428e6
+16 -1
View File
@@ -25,8 +25,23 @@ export type Schema = {};
type DirectusClient = ReturnType<typeof buildClient>;
/**
* Resolve a (possibly relative) URL against the current page origin.
*
* Runtime config supports relative paths like `/api` because the SPA always
* runs same-origin to its backends. The Directus SDK, however, calls
* `new URL(...)` internally and requires an absolute URL — so we resolve
* before handing it over.
*
* - `'/api'` → `'http://localhost:5173/api'` (in dev)
* - `'https://api.example.com'` → `'https://api.example.com/'` (passes through)
*/
function toAbsoluteUrl(maybeRelative: string): string {
return new URL(maybeRelative, window.location.origin).toString();
}
function buildClient(directusUrl: string) {
return createDirectus<Schema>(directusUrl)
return createDirectus<Schema>(toAbsoluteUrl(directusUrl))
.with(authentication('cookie', { credentials: 'include', autoRefresh: true }))
.with(rest({ credentials: 'include' }));
}