How to protect Next.js routes with getServerSideProps

3/03/2022

wchr

wachira

@__wchr

How to protect Next.js routes  with getServerSideProps

I have been working on a Saas product, it's a newsletter service. I decided to use Nextjs for its frontend.

I wanted to protect some routes like the dashboard unlike SPA React where you can write up a quick HOC and wrap your component and redirect if the token in local storage or wherever you are saving has expired, not valid or non-existent redirects to login to generate a new one. Note: you can do the same in Next but I did not want that approach.

Basically what I wanted to achieve was to make all API reads in the getServerSideProps, meaning I get everything I want before the page is loaded, which makes me avoid having spinners and stuff.

I was able to achieve that by making a profile API call based on the token I saved in the cookie but that meant I will have to replicate the same logic to always get a profile on each page so I wrote up this HOF(High order function) to handle that and here it is:

  • Basically create a file to house our HOF this can be hof/with-auth.tsx/js and paste this code.
  • Go to your page this can be dashboard.tsx/js update your getServerSideProps lifecycle to this

And that's it future me or someone out there that might need this.