Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Next.js 14 API Handler – Proper Request JSON body validation

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 any value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading