Search code examples
javascriptnode.jstypescriptexpresssession-cookies

After POST login and saved session in MongoDB - session is undefined


I am sending login data by POST with credentials: 'include' option from client server 5500 to backend server 3000. My session data is stored correctly in MongoDB thanks to 'connect-mongodb-session'. I store session in backend post request in that way:

req.session.user = user;
req.session.isLoggedIn = true;
return req.session.save((err) => {
    if (req.session.isLoggedIn) {
        res.status(201).json({
                success: true,
                message: "You are logged in !",
                url: "/client/home.html",
                session: req.session
            })

Maybe the key information is that I am using Typescript to backend. Maybe I should declare some how that session globally? I am doing something like this, maybe this is not enough?:

import { SessionData } from 'express-session';
import User from './user';


declare module 'express-session' {
    interface SessionData {
        user: User,
        isLoggedIn: boolean
    }
};

export default SessionData;

And I try to use that stored session from GET route or other places, but in that GET route express-session creates a NEW SESSION, why? Express should use that session where are variables isLoggedIn and User. After creating a new session req.session.isLoggedIn and req.session.user of course are undefined and I can't verify that user is loggedIn or not.

getHome(req: Request, res: Response) {
    console.log(req.session);   // that session has not "isLoggedId" and "user" variables
    res.json({ isLoggedId: req.session.isLoggedIn, user: req.session.user }) //this response an empty {}
    // res.json({ value1: "home11", value2: "home21" })
}

Why express-sessions create a new session?

And for the end: my middlewares config, maybe there will be something helpful:

middlewares: [
    cors(
        { 
            origin: true, 
            credentials: true 
        }
    ),
    cookieParser(),
    session(
        { 
            secret: 'my secret', 
            resave: false,
            saveUninitialized: false,
            proxy: false,
            rolling: true,
            store: store,
            cookie: {
                // httpOnly: false,
                maxAge: 36000000,
                // sameSite: 'strict',
                secure: !true
              },
            // genid: (req: express.Request): string => '',
        }),
    express.json({ type: "application/json" }),
    express.urlencoded({ extended: true }),
]

EDIT: Please look at my frontend, maybe here is something wrong

const loginBtn = document.getElementById('post-btn');
const loginInput = document.getElementById('login');
const passwordInput = document.getElementById('password');


login = async (clickEvent) => {
    clickEvent.preventDefault();
    let url = 'http://localhost:3000/login';
    await axios.post(url, { login: loginInput.value, password: passwordInput.value }, {
        // headers: {
        //   'Content-Type': 'application/json'
        // },
        withCredentials: true
      })
    .then(response => {
        if (response.data.success) {
            window.location.href = response.data.url;
            // console.log(response.data.session);
        } else {
            document.getElementById('message').innerHTML = response.data.message
        }
    })
    .catch(err => {
        document.getElementById('message').innerHTML = err
    });
};

document.getElementById('post-btn').addEventListener('click', login);

Solution

  • I found a solution. My Frontend was working on Liveserver, it is a Visual Studio Code extension. Probably that Liveserver somehow was blocking saving cookies on browsers. So I put the frontend server on express (I am not using any framework, just Vanilla Javascript) and now everything is working :)

    Probably if I used framework like Vue or React I should not had been this problems. :)