NextJS API Request Query params with TypeScript

Viewed 52

I'm building a REST API with NextJS and I'm wondering how to make the query parameters for one of my endpoints type-safe with TypeScript.

The endpoint I am currently working on is used to validate the uniqueness of a users' email when signing up: /api/users/validate-email, and I am sending an email string as a query parameter like this: /api/users/validate-email?email=someEmail@email.com.

Inside of the endpoint handler, I access the email from the query parameters as follows:

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const { email } = req.query;
};

export default handler;

However, with this setup de-structuring email from req.query is not type-safe and this is where I am stuck.

I have come up with a solution by extending the NextApiRequest type as follows:

type NextApiRequestValidateEmail = NextApiRequest & {
    query: {
        email: string;
    }   
}

const handler = async (req: NextApiRequestValidateEmail, res: NextApiResponse) => {
  const { email } = req.query;
};

export default handler;

This seems to work, but I'm not sure if it's the recommended way to do this and I can't seem to find anything about this in the documentation. So I am asking if this is the proper approach and if not, how does one go about declaring a type for an endpoints query parameters?

Thank you very much in advance!

0 Answers
Related