Next.js API request parameters validate

Viewed 27

What is the easiest/most recommended way to validate GET API query parameters?

For example we have a path: /pages/api/person/[id].ts

Then we have the code to handle the request

export default function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    const { id } = req.query;
    ...

How can you be sure that a variable is a valid number? I know we can just write some simple conditions like "isNaN (id), Number (id)" etc, but is that really the right way? In other frameworks or languages we can define regexes for parameters already while defining paths, is there such an option in next.js (I didn't find a word about it in the documentation)? I know there are ajv, joi, yup validators, but they were created to validate full objects and I think using them for primitive types is overkill.

Is there any simple method without writing the mass boilerplate code? Maybe typescript can help? Or maybe it just doesn't make sense to validate it so thoroughly? Maybe should I just throw anything into Prisma and possibly handle exceptions? However, years spent with PHP, where you had to validate everything to avoid errors such as SQLInjection or XSS tell me that this isn't the best idea.

0 Answers
Related