hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.62k stars 65 forks source link

getServerSideProps api call #147

Closed m4tta closed 2 years ago

m4tta commented 3 years ago

So how exactly do I get the returned JSON from one of my API routes when trying to run the handler in getServerSideProps?

hoangvvo commented 3 years ago

I am not sure that I understand. Could you please describe your use case in more detail?

m4tta commented 3 years ago

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?

hoangvvo commented 3 years ago

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)
}
nemanjam commented 2 years ago

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;

image

hoangvvo commented 2 years ago

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;

image

Can you try the TypeScript section https://github.com/hoangvvo/next-connect#typescript? The types you want to use can be found here:

image