Search code examples
node.jsexpressauthenticationexpress-session

express-session | req.session always empty for every request even after created


the problem is i cannot access the protected route even after logged in, because the middleware checks that there is no user session to access that protected route.

express-session

Here is the session middlewware

app.use(session({
    secret: "secret",
    store: store,
    saveUninitialized: false,
    resave: false,
    cookie: {
        // secure: true,
        maxAge: 1000 * 60 * 10,
        sameSite: "none"
    }
}))

Api middleware

client supposed to receive the fail message if not logged in, otherwise it continues to the chatRouter.

Here is the route i protected for user must login

const user = (req, res, next) => {
    if(req.session.user){
        console.log(`Dari middleware: ${req.session}`)
        next()
    } else {
        // res.redirect("/login")
        // console.log("Sesi chat: " + req.session);
        res.json({
            session: req.session,
            message: "fail"
        })
    }
}

app.use("/chat", user, (chatRouter));

When i sent a request to "/chat" after successfully logged in, i always got into that "fail" message.

front-end api call

axios.post(`${api}/user/login`, inputJson, {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json',
      },
    })
    .then(response => {
        if (response.status !== 200) {
          throw new Error('Error, status ' + response.status);
        }
        window.location.href = "/chat";
      })
    .catch(error => {
        console.log(error);
      });

Response i got

message: "Login succesfully",
session: {
  cookie: {…}, 
  user: {…}
},
[[Prototype]]: Object

But then, when i try to access the "/chat" route, it returns

{session: {…}, message: 'fail'}
message: "fail",
session: {cookie: {…}}, //The user session is missing here
[[Prototype]]: Object

I tried using http client software like postman & insomnia, the session thing is working normally, i cannot access the /chat before login, and im able to access it after logged in(works as expected).

But when i tried calling the api from my website, it happens like that, i still cant access the /chat after logged in an account.

Please help if you know the solution, i have been struggling here for hours 🗿.

Node version: 18.17.0 Express-session: 1.17.3 Express: 4.18.2


Solution

  • dayyum 3 days im working on it, the cause of my req.session always empty is because my front-end website (react) is running over http while my server is working over https, that made my website can't receive or send any cookie to my server.

    i'm solved this with changing my react website to run over https (from http://localhost:5173, to https://localhost:5173), using mkcert for localhost and config it in vite.config. now my website can receive and send cookies from my api, and the session working normally.

    here is the config for vite.config.js

    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import fs from 'fs';
    
    // https://vitejs.dev/config/
    export default defineConfig({
      server: {
        https: {
          key: fs.readFileSync('./.cert/key.pem'),
          cert: fs.readFileSync('./.cert/cert.pem'),
        },
      },
      plugins: [react()],
    });
    

    to make the certificate for localhost, u have to install mkcert first. and run these command from your vite.config.js directory.
    run command mkcert -install,
    then run command mkdir -p .cert && mkcert -key-file ./.cert/key.pem -cert-file ./.cert/cert.pem 'localhost'