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

redirecting in getServerSideProps middleware #194

Closed raphaelbadia closed 2 years ago

raphaelbadia commented 2 years ago

Hello,

the documentation indicates that we can't redirect using res.redirect() in a middleware.

DO NOT use response function like res.(s)end or res.redirect inside getServerSideProps.
// page/index.js
const handler = nc()
  .use((req, res) => {
    // BAD: res.redirect is not a function (not defined in `getServerSideProps`
    res.redirect("foo");
  })
  .use((req, res) => {
    // BAD: `getServerSideProps` gives undefined behavior if we try to send response
    res.end("bar");
  });

export async function getServerSideProps({ req, res }) {
  await handler.run(req, res);
  return {
    props: {},
  };
}

I am making an authentication middleware that should redirect to the login page when the token is expired and stop the middleware chain if the user is not authenticated. But I can't seem to find a solution to handle that from the middlewares. How should I do this ?

Thanks in advance !

hoangvvo commented 2 years ago

You must return redirect property for that: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#redirect

hoangvvo commented 2 years ago

This would be solved in the upcoming version https://github.com/hoangvvo/next-connect/pull/196

import { createRouter } from "next-conect";
const router = createRouter();
router.get(() => {
  return {
    redirect: {
      destination: "/",
      permanent: false,
    },
  };
});

export async function getServerSideProps({ req, res }) {
  return router.run(req, res);
}
raphaelbadia commented 2 years ago

Very interesting. Currently my workaround was really ugly : in my middlewares, I use the function next like so :

return next({
      redirect: { destination: APP_ROUTES.AUTH.LOGIN, permanent: false },
    });

this throws an error, so I can catch it in my getServerSideProps and return the error object 😔

I will follow the upcoming version with great interest, thanks for the update !