Next.js Discord

Discord Forum

Can I create a global getServerSideProps error handler? (Page router)

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
I have TONS of pages that use getServerSideProps. The API we use times out from inactivity and sends a 401. I have an axios interceptor that detects the 401 and redirects to the login page with a toast message "You've been logged out due to inactivity". The interceptor doesn't work inside of getServerSideProps because, well... it's not running in a browser window yet. LOL

At present, I was able to set up one of the pages to return a redirect if the 401 error occurs. The trouble is... I now have 50+ pages that use getServerSideProps and I honestly have no desire to have to add that code to each page...especially because each page has its own unique things that are happening inside of the function.

To use jQuery as an example, it's possible to run
$.ajaxSetup()
and assign a function for a 401 status code. This will affect all ajax calls in the rest of the app to execute that function if the call comes back with a 401.

My question is this: Can I augment, create, or assign a callback globally that will handle when getServerSideProps throws a 401? (or any error, for that matter?)

I saw an earlier post that says middleware is involved when the response comes back (before getting to the getServerSideProps page)... perhaps that's the place to handle it? If that's the case, does middleware know which page is executing at the time?

Thanks!

0 Replies