Express session create new session every request - node.js

I been search a lot and dont found solutions,
when I send request in postman everything goes well
but in my react app every request I send i get new session and I lossing my User info (using passport)
there is my backend session configuration:
app.use(cors({
credentials: true,
origin: 'http://localhost:3000',
methods:['GET','POST', 'DELETE', 'PUT'],
}));
//SESSION CONFIGURATION
const sessionStore = new MongoStore({
mongooseConnection: connection,
collection: 'sessions'
})
const sessionConfig = {
store: sessionStore,
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: { maxAge: 3600000, httpOnly: true, secure: false}
};
app.use(session(sessionConfig));
there is my axios configuration (fontend):
const instance = axios.create({
baseURL: 'http://127.0.0.1:5000/',
withCredentials: true
});
I really exhausted from this problem need some help thanks in advance
UPDATED
problem not solved but I see that my client side dont store any coockie in the browser and I get the coockie in the auth response

Related

Res header contaisn set Cookie but browser isn't storing it

I'm using express-session to store session cookie. I can see Set-Cookie connect.ssid under the response header but for some reason it is not getting stored in the cookie.
I'm wondering if this is a CORS issue, my app file looks like this. Should I change something here to make it work.
const session = require('express-session');
const config = require('config');
var MemoryStore = require('memorystore')(session);
module.exports = function (app) {
// app.use(
// session({
// secret: 'key sign',
// resave: false,
// saveUninitialized: false
// })
// );
app.use(express.json());
app.use(cors({ credentials: true }));
enter code here
app.set('trust proxy', 1);
app.use(
session({
saveUninitialized: false,
cookie: { maxAge: 86400000 },
store: new MemoryStore({
checkPeriod: 86400000
}),
resave: false,
cookie: { secure: false },
secret: config.get('sessionStorage')
})
);
app.use('/api/users', users);
Here is how I fixed this.
Add SSL to both frontend and backend.
If it is self-signed, ensure browser trust it. For example, if you're using mac, go to keychain, select specific certificate and select always trust option.
Restart the system. Only then SSL will be properly set otherwise there would still be insecure badge in the navigations.

Express session don't persist

I was making a React project, and I was using Express for backend. I set http://mini-api.moonlab.ga as a virtual host for Express server.
I sent a HTTP Request to express server with Fetch:
fetch("http://mini-api.moonlab.ga/login/", {
credentials: "include"
})
and as I expected there was a CORS error. So I installed cors package, and I set code like this in Node.js:
app.use(cors({
origin: true,
credential: true
}));
And I respond to client from server like this:
app.get("/login", (req, res) => {
const session = req.session;
if (session.miniAccount == undefined) {
session.miniAccount = Math.floor(Math.random() * 1000000);
}
res.writeHead(200, {"Access-Control-Allow-Credentials": true});
res.write(String(session.miniAccount));
res.end();
})
After I did like this, there wasn't any CORS error, but the session don't persist. When I send a request again, the session data keeps changes.
Well how to make session persist?
Server's session code:
app.use(express_session({
secret: secret.app_key,
resave: false,
saveUninitialized: true
}));
You may try setting a maxAge value inside cookie
...
const session = require("express-session");
...
app.use(
session({
secret: secret.app_key,
resave: false,
saveUninitialized: true
cookie: {
maxAge: 3600000 //session expires in 1 hr
}
})
);
I solved it myself by editing package.json.
I added "proxy": "mini-api.moonlab.ga" in package.json.
Than I edited fetch().
previous
fetch("http://mini-api.moonlab.ga/login")
new
fetch("/login")
And it worked.

What is the best time to set MaxAge for my cookies in my REST Api

What is conventional time to set (MaxAge) for my cookies in my Rest Api and I am using connect-mongo package to save the session on My mongodb, How do i destroy of delete the session from my mongodb once the user logged out.
The setup for my cookie is
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
store: new MongoStore({
mongooseConnection: mongoose.connection
}),
cookie: {
maxAge: 60000 * 30
}
}));
And the for the authentication am using passport

Express session sometime lost the session without logout [mobile app]

I used express-session for my Node.js application with these options
app.use(
session({
secret: "mysecret",
resave: true,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
cookie: {
httpOnly: false,
expires: new Date(253402300000000)
}
})
);
and sometime when I update the mobile app due to changes the session got lost and I have to logout and login again.

Node.JS with RedisStore session timeout

i'm using Redis to store sessions in my node.js app, hosted on heroku, but redis is keeping the session stored, how can i make them expire automatically?
My express app is configured this way:
var app = express.createServer(
express.static(__dirname + '/public', { maxAge: 31557600000 }),
express.cookieParser(),
express.session({ secret: 'secret', store: new RedisStore({
host: 'myredishost',
port: 'port',
pass: 'myredispass',
db: 'dbname'
})})
);
As the Connect session middleware docs state, you need to set the maxAge property on the cookie object:
express.session({ secret: 'secret', store: ..., cookie: { maxAge: 60000 }});
Read more about that here: http://senchalabs.github.com/connect/middleware-session.html
They will expire based on the cookie if you're using req.session.cookie.maxAge.

Resources