Closed m4tta closed 2 years ago
I am not sure that I understand. Could you please describe your use case in more detail?
When you call one of your NextJS API routes like described here
https://github.com/hoangvvo/next-connect#runreq-res
await handler.run(req, res);
If that API route returns JSON. How do you access that JSON data returned from the handler?
Okay I understood. handler.run
is getServerSideProps is not mean to send a response (so you probably don't want to call res.end or similar in there). It is only used to allow middleware to "decorate" (add properties like req.user
to req
).
Having said that, if you do some calculation in your middleware and want to retrieve it after handler.run
, you can attach the result to either req
or res
.
const middleware = async (req, res) => {
req.result = await doSomething(req, res);
}
const handler = nc().use(middleware);
export async function getServerSideProps({ req, res }) {
await handler.run(req, res);
console.log(req.result)
}
What about types?
export const getServerSideProps: GetServerSideProps = async ({ req, res, params }) => {
const id = Number(params?.id);
// try catch...
const handler = nc(ncOptions).use(async (req, res, next) => {
req.result = await getPostWithAuthorById(id);
next();
});
await handler.run(req as NextApiRequest, res as NextApiResponse);
const post = req.result;
What about types?
export const getServerSideProps: GetServerSideProps = async ({ req, res, params }) => { const id = Number(params?.id); // try catch... const handler = nc(ncOptions).use(async (req, res, next) => { req.result = await getPostWithAuthorById(id); next(); }); await handler.run(req as NextApiRequest, res as NextApiResponse); const post = req.result;
Can you try the TypeScript section https://github.com/hoangvvo/next-connect#typescript? The types you want to use can be found here:
So how exactly do I get the returned JSON from one of my API routes when trying to run the handler in getServerSideProps?