Implement Protected Routes in NextJS

2021-01-20 -- views 3 min read


Protecting Routes from unauthenticated users is a crucial part of any app.

In this blog, I’ll show you exactly how to do that with your NextJS pages using Higher-Order Components 1

There can be several ways of authenticating a user like using cookies or JWT tokens.2

I’ll be using JWT token as an example, where the accessToken is stored in the localStorage

Let’s consider a page “/dashboard”. This page should be only accessed by authenticated users

In our Dashboard.jsx

1// pages/dashboard.jsx 2import withAuth from "HOC/withAuth.js"; 3const Dashboard = ({ user }) => { 4 return ( 5 <div> 6 <h1>Dashboard</h1> 7 <h2>{user.name}</h2> 8 </div> 9 ); 10}; 11 12export default withAuth(Dashboard);

Notice that we are importing withAuth.jsx and exporting the page by passing it as an argument. That is all we need to do for our pages.


In our withAuth.jsx

I’ll show you two methods of implementations:

  • Method 1: We don’t verify the token

  • Method 2: We verify the token

Method 1: (We don’t verify the token)

1// HOC/withAuth.jsx 2import { useRouter } from "next/router"; 3const withAuth = (WrappedComponent) => { 4 return (props) => { 5 // checks whether we are on client / browser or server. 6 if (typeof window !== "undefined") { 7 const Router = useRouter(); 8 9 const accessToken = localStorage.getItem("accessToken"); 10 11 // If there is no access token we redirect to "/" page. 12 if (!accessToken) { 13 Router.replace("/"); 14 return null; 15 } 16 17 // If this is an accessToken we just render the component that was passed with all its props 18 19 return <WrappedComponent {...props} />; 20 } 21 22 // If we are on server, return null 23 return null; 24 }; 25}; 26 27export default withAuth;

Method 2: We need to verify the token.

1// HOC/withAuth.jsx 2import { useRouter } from "next/router"; 3import { useEffect, useState } from "react"; 4import verifyToken from "services/verifyToken"; 5 6const withAuth = (WrappedComponent) => { 7 return (props) => { 8 const Router = useRouter(); 9 const [verified, setVerified] = useState(false); 10 11 useEffect(async () => { 12 const accessToken = localStorage.getItem("accessToken"); 13 // if no accessToken was found,then we redirect to "/" page. 14 if (!accessToken) { 15 Router.replace("/"); 16 } else { 17 // we call the api that verifies the token. 18 const data = await verifyToken(accessToken); 19 // if token was verified we set the state. 20 if (data.verified) { 21 setVerified(data.verified); 22 } else { 23 // If the token was fraud we first remove it from localStorage and then redirect to "/" 24 localStorage.removeItem("accessToken"); 25 Router.replace("/"); 26 } 27 } 28 }, []); 29 30 if (verified) { 31 return <WrappedComponent {...props} />; 32 } else { 33 return null; 34 } 35 }; 36}; 37 38export default withAuth;

Footers:


Wasn’t that easy!

I hope this blog helped you. If you got any queries or feedback then let me know 😀


Found this blog helpful? Share it with your friends!