cms icon indicating copy to clipboard operation
cms copied to clipboard

Fix/auth type safety

Open VasuS609 opened this issue 10 months ago • 0 comments

Problem

The validateUser function in src/lib/auth.ts uses as any when returning API responses, completely bypassing TypeScript's type checking:


typescriptconst data = await response.json();

return data as any; // No validation!

Risk

If the external API returns malformed data (missing userid or name), it silently passes through and crashes later during JWT generation:


const user = await validateUser(email, password);

const jwt = await generateJWT({ id: [user.data](http://user.data/).userid }); 

// TypeError: Cannot read property 'userid' of undefined

What I have Implemented


const data = await response.json();

// Validate response structure

if (!data?.data?.userid || !data?.data?.name) {

  console.error('Invalid API response structure:', data);

  return { data: null };

}

// Return validated, typed data

return {

  data: {

    name: [data.data.name](http://data.data.name/),

    userid: [data.data](http://data.data/).userid,

    token: [data.data](http://data.data/).token || '',

  }

};

Benefits

  1. Now malformed responses are caught immediately and fail gracefully instead of causing undefined crashes.

  2. Type Safety: TypeScript properly validates return types

  3. Fail Fast: Invalid API responses caught at validation, not during JWT creation

  4. Better DX: IDE autocomplete works correctly, safer refactoring

VasuS609 avatar Jan 16 '26 09:01 VasuS609