'How to req.query in Prisma?
I am having some trouble with req.query in my nextjs dynamic API route.
The following code works where id is fixed (in this case "2")
import prisma from "../../../lib/prisma"
export default async function handler (req, res) {
if (req.method === 'GET') {
try {
const data = await prisma.product.findUnique({
where: {
id: 2
}
})
return res.status(200).json(JSON.stringify(data));
} catch (err) {
console.log(err);
return res.status(500).json({msg: 'Something went wrong in fetching id query - error 500'});
}
} else {
return res.status(405).json({ msg: 'Method not allowed - error 405' });
}
}
This would perform a GET request and I would receive this successfully:

However, what I want is to perform this GET request dynamically. But, if I changed the id with req.query.id so that I can GET individual request on the server based on the id parameter, it throws an error 500.
Any hints as to how to resolve this?
Solution 1:[1]
Problem resolved - the query requires to be parsed before being read. The solution is to provide const id = JSON.parse(req.query.id) and the pass the id into where { id: id }.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Beaumont |
