title: How to handle errors inside getServerSideProps in Next.js using next-connect
body: <p>I'm using Next.js and <a href="https://github.com/hoangvvo/next-connect" rel="nofollow noreferrer">next-connect</a> to handle middlewares.</p>
  <p>But I'm having problems trying to handle errors when I use several middlewares inside <code>getServerSideProps</code>.</p>
  <p>This is the code I have inside getServerSideProps, I just created a handler using several middlewares so then all of them run, the authentication is successful and the user data should be passed to the response, but if any fails, the error should be catched and return a redirect to <code>'/login'</code> page.</p>
  <pre><code>import nextConnect from 'next-connect';
  import { openDBConnection, retrieveUserInfo } from '@/middlewares/database';
  import { verifySessionCookie } from '@/middlewares/firebaseSession';
  ...
      export const getServerSideProps = async ({ req, res }) =&gt; {
          const handler = nextConnect()
              .use(verifySessionCookie)
              .use(openDBConnection)
              .use(retrieveUserInfo);
          try {
              await handler.run(req, res);
              return {
                  props: {
                      user: req.user,
                  },
              };
          } catch (e) {
              console.log(e);
              return {
                  redirect: {
                      destination: '/login',
                      permanent: false,
                  }
              };
          }
      }
  </code></pre>
  <p>I didn't define any try/catch block in any of the middlewares, so if an error happens it can be handled in any api page or getServerSideProps block.</p>
  <p>Every seemed to be ok when there was only one middeware <code>verifySessionCookie</code> the error is returned when <code>await handler.run(req, res)</code> is called and then handled in the catch block.</p>
  <p>But when using the 3 middlewares as it's shown in the piece of code, if the first middleware fails (<code>verifySessionCookie</code>) the error is not handled in the catch block.</p>
  <p>I've tried to make the <code>next()</code> call in every middleware, using a <code>finally</code> clause), in this way the error is catched inside getServerSideProps but:</p>
  <ul>
  <li>verifySessionCookie executes, it fails.</li>
  <li>openDBConnection executes, it doesn't fail.</li>
  <li>retrieveUserInfo executes, it fails.</li>
  </ul>
  <p>Maybe I'm doing something wrong here, or maybe next-connect is not intended to be used this way. I don't know how can I handle the error in case that one middleware, and all the rest is not executed. Perhaps I should be calling independent async functions with (req, res) parameters inside the getServerSideProps and stop using this next-connect plugin.</p>