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 :

JavaScript

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

JavaScript

And MyAuthComponent.js

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement