How can I maintain Session in reactJs NodeJs web APP?

Viewed 91

I'm developing a register/login website which includes all features to make it work in an efficient and secure way using reactJS, NodeJS and Mysql. Everything was working fine until I used express-session. In fact, when a user logs in, he will be redirected to a home page (obviously a session will be created) but when the user refreshes the page, It is expected to stay on the home page but the behavior I got is losing the session, thus being redirected to login page. I looked for a fix and I already tried enabling credentials with Axios in the frontEnd and Cors in the backEnd but the problem is persisting. This is my code: server.js

const express = require('express');
const app = express();
const mysql = require('mysql2');
const cors = require('cors');
const validator = require('validator');
const {body, validationResult} = require('express-validator');
const session = require('express-session');
const cookieParser = require('cookie-parser');

app.use(express.json());
app.use(cors({
    origin: ['http://localhost:3000'],
    methods: ['GET', 'POST'],
    credentials: true,
}
));

app.use(express.urlencoded({extended: true}));
app.use(cookieParser());
app.use(session({
    name: 'session',
    secret: 'crud',
    resave: false,
    saveUninitialized: false,
    cookie: {
        expires: 60 * 30,
        sameSite: 'strict',
    }
}
app.post('/login', (req, res) => {
    const mail = validator.escape(req.body.mail);
    const pass = validator.escape(req.body.pass);
    const sqlSelect = 'SELECT * FROM login WHERE mail = ? AND pass =  ?';
    db.query(sqlSelect, [mail, pass], (err, result) => {
        if (err) {
            console.log(err);
        }

        if (result.length > 0) {
            req.session.user = result;
            req.session.loggedIn = true;
            console.log(req.session.user);

            res.send({message: 'success', session: req.session});
            
        }
        else {
            res.send({message: 'Wrong combination Email/Password !'});
        }
    })
    
});
app.get('/login', (req, res) => {
    console.log(req.session.user);
    if (req.session.user){
        res.send({
            session: req.session,
            message: 'logged'
        });
    }
    else {
        res.send({
            message: 'Not logged'
        });
    }
});

app.js (login page)

 Axios.defaults.withCredentials = true;
    
    const onSubmit = () => {
        Axios.post('http://localhost:9001/login', {
            mail,
            pass,
        }).then((response) => {
            console.log(response.data.message);
            if (response.data.message === 'success') {
                history.push('/home');
            }
            else {
                setMessage(response.data.message);
            }
            
        });
    };

home.js

export default function Home() {
    const [user, setUser] = useState('');
    const history = useHistory();
    

    
    
    useEffect(() => {
        
        Axios.get('http://localhost:9001/login', {withCredentials: true}).then((response) => {
            console.log(response.data.message);

           
            if (response.data.message === 'logged'){
                setUser(response.data.session.user[0].mail);
            }
            else {
                history.push('/');
            }
        })
    //eslint-disable-next-line
    }, []);
    return (
        <div>
            <p>{user}</p>
        </div>
        
    )
}

I hope someone is able to suggest some fix to this. I know I can use localStorage but I want to use the session instead.

0 Answers
Related