Skip to content

Bug: Two null-safety issues in src/lib/api/search.tsgetSearchBaseUrl() misses undefined env var, autocomplete() can return undefined as AutocompleteResponse #1248

@roshinit-a

Description

@roshinit-a

Description

Two related null-safety bugs exist in src/lib/api/search.ts that can cause hard-to-debug runtime crashes.


Bug 1: getSearchBaseUrl() doesn't guard against undefined

Lines 10–17

export function getSearchBaseUrl() {
    if (env.PUBLIC_SEARCH_BASE_URL == '') { // ← only catches empty string, not undefined
        throw new Error('PUBLIC_SEARCH_BASE_URL is not set...');
    }
    return env.PUBLIC_SEARCH_BASE_URL; // ← can return undefined if the env var is missing
}

SvelteKit types env.PUBLIC_SEARCH_BASE_URL as string | undefined. The guard only catches the '' case. If the env var is missing from .env, getSearchBaseUrl() returns undefined, and the immediate caller (createSearchApi) does new URL(undefined) — which throws an unreadable TypeError instead of the clear error message already written in the throw.

Fix: Change == '' to !env.PUBLIC_SEARCH_BASE_URL to cover both '' and undefined.


Bug 2: autocomplete() casts undefined to AutocompleteResponse

Line 31

export const autocomplete = async (
    query: AutocompleteQuery,
    fetch: typeof window.fetch
): Promise<AutocompleteResponse> => {
    const api = createSearchApi(fetch);
    const response = await api.autocomplete(query);
    return response.data as AutocompleteResponse; // ← no null check
};

response.data is undefined when the search API returns an error or non-200 response. The as AutocompleteResponse cast silences TypeScript, but any caller that does .options.map(...) on the result will crash with TypeError: Cannot read properties of undefined (reading 'map').

Fix: Return a safe fallback: return (response.data ?? { options: [] }) as AutocompleteResponse;


Proposed Fix (both bugs together, same file)

 export function getSearchBaseUrl() {
-    if (env.PUBLIC_SEARCH_BASE_URL == '') {
+    if (!env.PUBLIC_SEARCH_BASE_URL) {
         throw new Error(
             'PUBLIC_SEARCH_BASE_URL is not set. Please set it in your environment variables.'
         );
     }
     return env.PUBLIC_SEARCH_BASE_URL;
 }
-    return response.data as AutocompleteResponse;
+    return (response.data ?? { options: [] }) as AutocompleteResponse;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions