Skip to content
Advertisement

Nested routes authentication in NextJs

Is there any way we can Authenticate all the nested routes ?
In my project I have routes which needs authentication and routes which can be accessible without authentication.
For eg.
/admin => needs authentication
/admin/posts => needs authentication
/admin/posts/1 => needs authentication
/admin/users => needs authentication
and so on..
/view => can access without authentication
/view/songs => can access without authentication
/view/posts => can access without authentication
Things which I have tried :
HOC : need to include it in every route I create inside admin. Is there any way we can do it in common place ?
getServerSideProps : same as above

is there any way to do this in one common file ?

Advertisement

Answer

You can achieve this in multiple ways, just a couple of inputs :

If you are using next >= 13 with the new app directory routing convention you can use the layout.js file in the root of /admin folder :

   export default function RootLayout({ children }) {
      // your logic to  check if the user is logged 
      if(/* user is logged */){
          return (
            <html>
              <head></head>
              <body>{children}</body>
            </html>
          )
      }else{
          return <p>Must be authenticated</p> // show login?
      }
    }

Otherwise you can use a similar logic inside the _App.js

import { useRouter } from 'next/router';
import {MyAuthComponent} from 'auth/path' // your login component

export default function MyApp({ Component, pageProps }) {
    const router = useRouter();
    const currentPath = router.asPath
    const isPublicRoute = currentPath.includes('view') // your logic to check if the current route is public
    if(isPublicRoute ){
        return  <Component {...pageProps} />
    }else{
      return (
          <MyAuthComponent>
              <Component {...pageProps} />
          </MyAuthComponent>
      )
    }
}

And MyAuthComponent.js

  export default function MyAuthComponent({ children }) {
      // your logic to  check if the user is logged 
      if(/* user is logged */){
          return (
            <html>
              <head></head>
              <body>{children}</body>
            </html>
          )
      }else{
          return <p>Must be authenticated</p> // show login?
      }
    }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement