Reputation: 765
I'm starting to build a next.js application and i'm using redux. I read a lot about authentication in next.js and specifically with redux. Let's say I have a /login page and a /private page. And my redux store contains isAuthenticated state. So, as i see it, i need to think of the following scenarios:
When navigating to /private through the address bar (SSR) , i should redirect to /login.
When already in /private and the isAuthenticated changed to false.
After logging in successfully in /login, update isAuthenticated state and redirect to /private page.
Did i miss some important possible scenario (UX and security wise)?
Regarding those cases, I have a few questions for the experts here:
For scenario number 1, i implemented an authentication check in getinitialprops (only when ctx.req is not null). If the user is not authenticated, i redirect him with 302 response to the /login page. Is that ok?
About scenario number 2, where should i implement this logic? What is the best practice? I can think of implement the check in getinitialprops, in render() function, in componentDidUpdate...
Should i redirect after calling the redux action (authenticate), or in the redux action?
Should i fire the login request from within the redux action or in the handle function in component, and on success call the redux action.
When redirecting, should i use Router.push or Router.replace?
Please help me to understand the best practice once and for all.
Upvotes: 2
Views: 4029
Reputation: 608
This is based on experience:
Yes, this is okay. It does what it needs to do.
Definitely getInitialProps. What we did is we made a helper that can be used by both SSR and CSR components. What the helper does is it accesses the Cookies for both instances, that way, the auth state is consistent. There could be better ways but this is how we implemented it.
Depends on your team's protocol. For us, all side effects such as redirections, are allowed to be done inside the Redux Sagas.
I would suggest using Sagas as it is much more cleaner and gives you another layer to keep all your sideeffects in. But in your case, I would suggest keeping the actions clean and just do what it needs to do: change the state.
I would suggest Router.push
. Using replace would overwrite the top of the route stack and that may lead to undesirable effects when hitting back or what not. This would depend on your requirements should it be concerned about what happens when you hit back.
Don't overcomplicate things. Make it work and find better ways to do it after you actually make things work.
Upvotes: 1