I’m trying to build an api for an iOS app I’m working on. I’m using Next.js 14 for it and I got it working, for the most part but I’m a bit puzzled on how to properly validate the body of a Request. ESLint throws all kinds of errors and warnings at me and while I could "fix" most of them, there’s one I’m really unsure about:
Unsafe assignment of an
anyvalue
This happens when I say const body = await request.json();. I don’t understand how to fix this. The json() method returns any at this point but it’s immediately validated by calling validateRequest one line later.
I could cast it as RequestBody: const body = await request.json() as RequestBody; but that kind of defeats the point, doesn’t it?
Any ideas how to properly handle this?
// app/api/route.tsx
interface RequestBody {
name: string;
}
function validateRequest(object: any): object is RequestBody {
return (
(object as RequestBody) && typeof (object as RequestBody).name === "string"
);
}
export async function POST(request: Request) {
try {
// Warning: Unsafe assignment of an `any` value
const body = await request.json();
if (!validateRequest(body)) {
return new Response("Invalid Data", { status: 400 });
}
return Response.json({ message: body.name });
} catch {
return new Response("Bad Request", { status: 400 });
}
}
I’ve followed this answer for runtime validation of the data: https://stackoverflow.com/a/44078574/3134192
>Solution :
I suggest to use validation library such as Zod, Yup or Valibot. Using Zod you define your schema and you can validate the body with .parse or other methods. You can find more examples in the official docs.
Define your schema:
const User = z.object({
name: z.string()
});
Then you can validate the body with parse or safe parse method:
// will throw and error if body is not valid
User.parse({ username: "Ludwig" });
// will return object with object: {success: boolean, error: ZodError}
User.safeParse({ username: "Ludwig" });
Zod does much more you can even infer a type from your schema:
// extract the inferred type
type User = z.infer<typeof User>