DEV Community

Ata Parvin Ghods
Ata Parvin Ghods

Posted on

React Protected Routes (Next js & CRA) simple but efficient

Sometimes we need to hide pages/routes from the user and disabling their accessibility to those pages.
In this post I want to show you the easiest way(which I think it is) to do this.

1.I will start with create-react-app

// Create a new app
npx create-react-app route-app react-router-dom

// Run the created app
cd route-app
yarn start

// http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

2.In our main component(App.js) we will define our routes
(src/App.js)

import ProtectedRoute from './ProtectedRoute'
import { BrowserRouter, Switch, Route } from 'react-router-dom'

export default App = () => {
   return(
      <BrowserRouter>
        <Switch>
          <Route exact path='/posts' component={Home} />
          <ProtectedRoute exact path='/login' component={Login} />
          <Route path='/' component={NotFound} /> 
          //this is 404 page btw - no "exact" prop
        </Switch>
      </BrowserRouter>
   )
}
Enter fullscreen mode Exit fullscreen mode

As you can see we will create our route with a custom route component, So let's build that.

3.Our ProtectedRoute component
(src/ProtectedRoute.js)

import React from 'react'
import { Redirect, Route } from 'react-router'

export const ProtectedRoute = ({ component: Component, ...rest}) => {
    const userIsLoggedIn = true //our user logged in

    return(
        <Route 
            {...rest}
            render={(props) => {
                if(!userIsLoggedIn){
                    return <Component {...props}/>
                } else {
                    return <Redirect to={{ pathname: '/', state: {from: props.location }}} />
                }
            }}
        />
    )
}
Enter fullscreen mode Exit fullscreen mode

If our user is not logged in then show the Component(which is loggin page in this case because we don't want logged in user see the login in page), If not Redirect the user to home page.

This is how we protect route with react-router-dom

In Next Js we use HOC(high-order-component)

1.Create next app

// Create a new app
npx create-next-app route-app

// Run the created app
cd route-app
yarn dev

// http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

2.First We create HOC
(src/HOC/ProtectedRoute)

import { useRouter } from "next/router"

const ProtectedRoute = (ProtectedComponent) => {

   return (props) => {

      if (typeof window !== "undefined") {
         const Router = useRouter()

         const userIsLoggedIn = true

         if (userIsLoggedIn) {
            Router.replace("/")
            return null
         } else {
            return <ProtectedComponent {...props} />
         }
      }

      return null
   }
}

export default ProtectedRoute
Enter fullscreen mode Exit fullscreen mode

In this case we say if the user is logged in then redirect to home page else return the component

3.Make our page protected
(src/pages/login.js)

import ProtectedRoute from "../HOC/ProtectedRoute"

const Login= () => {
   return (
      <div>
          <a>Login Page</a>
      </div>
   )
}

export default ProtectedRoute(Login) //wrap our component in hoc
Enter fullscreen mode Exit fullscreen mode

That's all you need! Thank you

Top comments (7)

Collapse
 
almosaiki0 profile image
almokhtar

How dose that work .
If the business logic in the front end it too risky to do it like that.

Collapse
 
ataparvinghods profile image
Ata Parvin Ghods • Edited

Dear almokhtar
You are right my friend, everything in frontend is changable, BUT let's say you changed the code via browser and got access to admin's dashboard, there will be no data available for you and you cannot do/change anything cause you are not authorized. We make these routes private so normal people can't access to those routes but if they, they cannot harm your program or change anything.
In these code I put "userIsLoggedIn " as a boolean with true value but in a real program you could change that with authorization, So if the user authorized and got token then he/she can get access to those routes. Hope that you got the point

Collapse
 
almosaiki0 profile image
almokhtar

Thank you very much for your explanation.
I just want to say that if I got an access to the Admin Dashboard login site or something like this I could find out more information about your CMS and trying to look for Vulnerabilities . I will prefer to do the whole thing server Side. But your explanation is Great thanx

Collapse
 
luanau profile image
luanau

Returning ProtectedComponent when user is not logged in?!

Collapse
 
ataparvinghods profile image
Ata Parvin Ghods

Dear luanau.
We are returning protected component(login page), which means if user is not logged in you want to show user login page.
But this is an example you can change them on your own.
Hope I made it clear.

Collapse
 
luanau profile image
luanau

Thanks Ata.

Collapse
 
saravanakumar645 profile image
Saravana Kumar . V

When i implemented this, I got a empty white screen which is because the typeof window is undefined and the code returns null. How can i past that issue ?