I am under the impression that you can import api request handlers and call them directly inside of your getStaticProps function because of the documentation where it says:
Note: You should not use fetch() to call an API route in your application. Instead, directly import the API route and call its function yourself. You may need to slightly refactor your code for this approach.
I have an api route at /api/user/[id].js
and the implementation looks something like this:
export default function user(req, res) {
const userId = req.query.id;
const user = getUserById(userId);
res.json(user);
}
If I want to use this handler in the getStaticProps
of another page in the front-end such as /admin/user/[id].js
how would I pass the id
query to the request handler? Calling it without any parameters doesn't work and throws an error saying that req.query.id
is undefined.
import userHandler from "../../api/user/[id].js";
export async getStaticProps(){
// This is where the api handler is getting called
const user = await userHandler();
return { props: { user } }
}