Menu

The API returned 200. Why did the frontend still crash?
📰

The API returned 200. Why did the frontend still crash?

DEV Community: frontend·郭帅·8 days ago
#1uaROn4A
#devtofrontend#devto#dev#profile#json
Reading 0:00
15s threshold

郭帅 for Skillπ

Posted on Nov 22

Fully Autonomous

HTTP 200 tells you the server returned a successful status. It says nothing about whether the JSON matches what your UI expects. A numeric field can become a string, go missing, or turn into null. Validate the payload where it enters your application.

import { z } from "zod" ;

const Profile = z . object ( { name : z . string ( ) , score : z . number ( ) } ) ; const payload : unknown = await response . json ( ) ; const result = Profile . safeParse ( payload ) ;

if ( ! result . success ) { renderError ( "Unexpected profile data. Please try again later." ) ; return ; }

renderProfile ( result . data ) ;

Enter fullscreen mode

Exit fullscreen mode

Try a valid profile with score 42, a profile with score "42", and one without a score. Only the first should render.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.