Home > Enterprise >  req.session.user get undefined whenever i change anything on my server, and on the first i make a ca
req.session.user get undefined whenever i change anything on my server, and on the first i make a ca

Time:09-02

my code works but whenever i made a change in the server.js, the req.session.user turns undefined.

This also happens the first time i make a request from the front, i do get authenticate. but right after i dont get the user.name and cookie cause it reads undefined.

if I run it again, it works and it keeps working until i quit the server and start again. it repeats the same pattern, doesnt work first time, then it works.

i believe is related to the backend as any change in the backend gets session.user undefined,

server.js

const express = require("express");
const session = require("express-session");
const app = express();
const mysql = require("mysql2/promise");

app.use(express.json());
    
app.use(
  session({
    key: "userId",
    secret: "password",
    resave: false,
    saveUninitialized: false,
    cookie: {
      expires: 1000 * 60 * 60 * 24, 
    },
  })
);

app.use(
  cors({
    credentials: true,
    origin: ["http://localhost:3000"],
    methods: ["GET", "POST"],
  })
);
app.post("/login", async (req, res) => {
  const { userName, password } = req.body;
  

  try {
    const [result] = await db.query(
      `select * from user 
        where 
        user = ? and
        password = ? `,
      [userName, password]
    );

    if (result.length > 0) {
      req.session.user = {
        loggedIn: true,
        user_id: result[0].user_id,
        name: result[0].name,
      };
      res.send(req.session.user);
    } else {
      res.send({ message: "Wrong password or user" });
    }
  } catch (error) {
    console.error(error);
  }
});

// checking whats on the session
app.use((req, res, next) => {
  console.log(req.session.user);
  next();
});

// session retriving
app.get("/login", (req, res) => {
  req.session.user
    ? res.send({
        loggedIn: true,
        name: req.session.user.name,
        user_id: req.session.user.user_id,
      })
    : res.send({ loggedIn: false });
});

app.js

Axios.defaults.withCredentials = true;
useEffect(() => {
    
    Axios.get("http://localhost:3001/login").then(({ data }) => {
      setUser({
        loggedIn: data.loggedIn,
        name: data.name,
        user_id: data.user_id,
      });
      console.log(data);
    });
  }, []);

CodePudding user response:

Whenever you change server.js - your server gets restarted, and since you don't have a session store where your session is saved the session is lost everytime the server is restarted. (the session is kept only in memory)

When you check out session readme, https://github.com/expressjs/session it says:

Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing. For a list of stores, see compatible session stores.

So check out: https://github.com/expressjs/session#compatible-session-stores to find a store that might suit you.

CodePudding user response:

Since session are stored on memory it will reset everytime your backend got restarted. If you don't want that you can create one static session/token to use on DEVELOPMENT ONLY.

  • Related