I am trying to access user data after succesfull login and also from every component.This is how i login the user:
router.post("/user/login",(req,res,next)=>{
passport.authenticate('local', function(err, user, info) {
console.log(JSON.stringify(user)) // here i got user data
if (err) { return next(err); }
if (!user) { return res.send("fail"); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.send("success") // when client gets success message,it will do Router.push("/dashboard")
});
})(req, res, next);
})
Server configuration:
server.use(cookieParser())
server.use(bodyParser.json())
server.use(passport.initialize());
server.use(session({
secret: 'jumpingdonger',
resave: true,
saveUninitialized: true,
cookie : { secure : false, maxAge : (4 * 60 * 60 * 1000) }, // 4 hours
}))
//Passport Middleware
server.use(passport.initialize())
server.use(passport.session())
DashBoard page:
import Header from '../components/Header'
import Layout from '../components/MyLayout.js'
import React, { Component } from 'react';
import axios from 'axios';
import Router from 'next/router'
export default class DashBoard extends Component{
constructor(props) {
super(props);
this.state = {
};
}
componentWillMount(){
console.log(this.props)
}
logout =()=>{
axios.get('/api/user/logout').then((result)=>{
if(result.data=="success"){
Router.push("/")
}
})
}
render(){
if(this.props.userData == undefined){
return(
<Layout>
<p>First you must login!</p>
</Layout>
)
}else{
return(
<Layout>
<p>Welcome to your dashboard {this.props.userData.userName}</p>
<a onClick={this.logout}>logout</a>
</Layout>
)
}
}
}
DashBoard.getInitialProps = async function(context) {
if(context.req !=undefined){ // which means that we are from server
return {
userData:context.req.user
};
}else{
return{}
}
}
So after succesfull login,i am redirected to dashboard page.Now in dashboard component i am trying to get userdata on getInitialProps.The problem is since i am redirected by client using Router.push(),i cant get data on getInitialProps unless i dont refresh the page from browser.If i refresh,context.req.user is populated by user data.So how do i access userdata with client side routing from dashboard page and also every other page ? What i couldnt understand is, is this puting user data into a cookie which i can access from client or is this a server side session ?
thanks
EDIT: I solved the problem by transfering userData from server to client on succesfull login and seting a cookie in client side.I wonder is this a correct solution in this case ?
If user is logged in. passport will create user object in req for every request in express.
if (req.user) {
// logged in
} else {
// not logged in
}
In next.js when you use getInitialProps you have access to server with context.req.
like this:
static async getInitialProps({req}){
if(req){
// called on server
// here you can check for that user object
} else {
// called on client
}
}
However this cod will work if you have a SSR request in your next.js app (refresh page or put url and press enter).
You authenticate in server, so there is no way to find out if you have the same in front-end, Unless you use the token and verify the token in front-end as well. Have a look at Express session which will help you with cookies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With