Urgent.News

What's breaking now, across thousands of outlets.

World

TypeScript Does Not Protect Your API: Request Bodies Are Lies Until You Validate Them

You write a clean endpoint. The body is typed. The editor is happy. No red squiggles anywhere. type CreateUser = { name : string ; email : string ; age : number }; export async function POST ( req : Request ) { const body = ( await req . json ()) as CreateUser ; await User . create ( body ); return Response . json ({ ok : true }); } Then someone sends this: { "name" : "Mallory" , "email" :…

The article titled "TypeScript Does Not Protect Your API: Request Bodies Are Lies Until You Validate Them" discusses the limitations of TypeScript in ensuring the integrity of request bodies in APIs. The author emphasizes that TypeScript types only exist during development and are erased at runtime, leaving the program vulnerable to malicious or unexpected data.

They provide an example of a clean endpoint that types the request body using the CreateUser interface, but warns that this type alone does not guarantee data safety. The author then illustrates three potential issues that can arise from trusting the request body without validation: crashes caused by missing or invalid data, corrupt data being stored in the database, and privilege escalation through mass assignment.

They propose a solution using a schema library like Zod, which can validate the data at runtime and provide type safety as a bonus. The updated code example demonstrates how to use Zod to define a schema for the CreateUser object, parse the request body using the schema, and handle any validation errors by returning a 400 status code with detailed error information.

By validating the request body at the boundary between the client and the server, developers can ensure that only valid and expected data reaches the server, mitigating the risks of crashes, corrupted data, and privilege escalation.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in World

More from Sunday 8 November →