In the last few months, I have been working on Next.js applications. Although, there are many methods of implementing authentication workflows in next.js, but I didn’t find any tutorial that described implementing client side authentication logic in detail. But, with bits of information I gathered here and there and so many tries, I was able to figure it out. I have written this article to guide anyone who is interested in implementing something like this.
Below are the steps I took to achieve this using a higher order component, Context API and React hooks.
STEP 1: STORE AUTHENTICATION STATE
The first step is to use whatever method you are comfortable with to store authenticated user state. In my case, I used the React context API to store my authenticated user state, which I persisted in the local storage. There are many tutorials that detail how to use context API. But here, our focus is to redirect the user to another page if user is not logged in.
STEP 2: CREATE A NEW COMPONENT
Create a new file called ProtectedRoute.js and initialize it with the following lines of code. Notice there are two props — router and children. The router prop would be passed in from the _app.js file that would be created in the pages folder. The children is one of the commonly used props in react that refers to any child of the parent component. I would discuss this in the later part of this article, but for now, lets focus on creating a new component.
In my case, I had more routes that required the user to be logged in before they can access them than the ones that do not. Owing to this reason, I chose to keep a list of routes that do not need authentication which I have stored in a variable named unprotectedRoutes. If reverse is the case, you can choose to do the opposite of what I have done here.
STEP 4: WRITE LOGIC FOR REROUTING UNAUTHENTICATED USER
If the user is trying to access a route that needs authentication, the user should be redirected to the login page (or whatever page you deem fit as your project may require).
Notice the isBrowser function, it is used to distinguish between when you are on the server environment (NodeJS) and client environment (browser), because router.push only works on the browser.
STEP 5: CREATE/MODIFY _app.js
if you have an _app.js file in your pages folder already, all you need to do it modify appropriately, but if you don’t, create a file called _app.js in the pages directory. Do not attempt to call this file any other name as it is used by Next.js to initialize pages. Click here to read more. If you are using context API, here is a good place to wrap your context provider.
Import the ProtectedRoutes.js component we created in step 2 into the _app.js file. See output below.
To ascertain that everything works as expected, visit any route that is not on the unprotectedRoutes list and you should be redirected to the login page. Visiting any unprotected route should also direct you to the right pages.