Socket.io page refresh - node.js

I am making a one to one chat application using socket.io and mongodb, whenever I refresh the page a new socket connection is formed, whenever user joins the chat he needs to refresh the page at the beginning then only it starts receiving messages. Can anyone tell me how to avoid it?
I am using express-session to store the session.
var sessionInit = session({
name: 'userCookie',
secret: '9743-980-270-india',
resave: true,
httpOnly: true,
saveUninitialized: true,
store: new mongoStore({
mongooseConnection: mongoose.connection
}),
cookie: {
maxAge: 80 * 80 * 800
}
});
app.use(sessionInit);

Maybe not the best thing to do but you can use
window.location.reload();
when someone joins the chat so they don't have to do it by themselves

Related

Cookies was not sent when the request come from front-end

I am following Ben Awad full stack tutorial with same stack (
React
TypeScript
GraphQL
URQL/Apollo
Node.js
PostgreSQL
MikroORM/TypeORM
Redis
Next.js
TypeGraphQL
Chakra
)
But newer versions (the video was 2 years old), in 2:59:59, according to the video, when we make a register request through browser(client side) the qid cookies was supposed to get sent automatically but it doesn't work for me. Things work fine when I make request through my server (localhost port 5000, redirect to https://studio.apollographql.com/sandbox/explorer) but when it come to browser I successfullyy register the user but the cookies was not saved.
Here is the code I built in my server to set the cookies (redis connected):
app.use(
cors({
origin: ["http://localhost:3000", "https://studio.apollographql.com"],
credentials: true,
})
)
app.set("trust proxy", true);
app.use(
session({
name: "qid",
store: new RedisStore({ client: redisClient, disableTouch: true }),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 10, //10 years
httpOnly: false,
sameSite: "none",
secure: true, // cookie only works in https
},
saveUninitialized: false,
secret: "123456789",
resave: false,
})
);
Thanks guys and I appreciate you guys a lot.
I solved it: set sameSite: 'none' when you want to save cookie through sandbox and lax when you want to save it with browser.

Why can't I set cookies over HTTPS?

I have a server that has its own domain and is using HTTPS. I have a website that has its own domain and is using HTTPS as well.
On the home page of the website, there is a login button and a sign up button. Both buttons lead to forms to execute their respective tasks, and both forms send requests to the server that respond with cookies, or at least that's what they are supposed to do.
I am using express-session in combination with Redis to store the session ids. Here is the config for that (connectToRedis is simply a function that returns a RedisClient):
const RedisStore = connectRedis(session);
const redisClient = await connectToRedis();
app.use(
session({
store: new RedisStore({
client: redisClient,
}),
cookie: {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge: TEN_YEARS,
},
resave: false,
saveUninitialized: false,
secret: SECRET,
name: AUTH_COOKIE,
})
);
For some reason the cookies are not being sent in the requests. The Set-Cookie header isn't even showing up! I tried changing SameSite to none (article), but that didn't work.
This is my first time deploying a production website, so all this HTTPS stuff is kind of new to me.
Thanks for your help, and if you need any extra information, please let me know.
IMPORTANT UPDATE:
Finally, I have made some progress (all it took was a pizza break).
I added the path key to my cookie config and gave it the value of /. I also set proxy to true.
So now it looks like this:
const RedisStore = connectRedis(session);
const redisClient = await connectToRedis();
app.use(
session({
store: new RedisStore({
client: redisClient,
}),
cookie: {
httpOnly: true,
secure: true,
sameSite: "none",
maxAge: TEN_YEARS,
path: "/",
},
resave: false,
saveUninitialized: false,
secret: SECRET,
name: AUTH_COOKIE,
proxy: true,
})
);
With this, the cookie is finally appearing in the requests, but it isn't being set in the browser...

Keep user sessions logged in on Node.js server restart

I am using express-session for a login system for users on my Node.js web application. My issue is that every time I make an update and restart the Node.js server, all the users are logged off which is not ideal behaviour (there are multiple users logged on via the local network and I would like to not have to log them back on each time there is a restart).
From my understanding I could use something such as connect-pg-simple (for reference I am using a postgres database with my node web app) to keep users logged in on server restart but I am unsure of how to implement this.
I know it would be something along the lines of:
app.use(session({
store: new (require('connect-pg-simple')(session))({
// Insert connect-pg-simple options here
}),
secret: 'secret',
resave: false,
saveUninitialized: true
}));
But I do not know what options to use or how to save the users session even on server restart.
Yes you are on the right track.
Open your database and create a table named session. See: https://github.com/voxpelli/node-connect-pg-simple/blob/HEAD/table.sql
Add the connect-pg-simple code like you posted
Pass the postgres pool you are using from node-pg.
const session = require('express-session')
const PGSessionStore = require('connect-pg-simple')(session)
const pg = require('pg')
const pool = new pg.Pool({
user: process.env.PG_USERNAME,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT
})
app.use(session({
store: new PGSessionStore({
pool: pool,
tableName: 'session'
}),
secret: process.env.COOKIE_SECRET,
cookie: {
secure: false,
httpOnly: true,
sameSite: true,
maxAge: 24 * 60 * 60 * 1000
},
saveUninitialized: true,
resave: false
}))
Your session is stored on the app runtime, so on refresh, it resets back every other data it might be holding at runtime on server restart

Problem understanding how express session saves client in memory

I am currently building a rest api with express backed up with a mongo database. At the moment, I have setup a simple authentication process which saves a session object in the mongo database.Thing is I don't send back anything to the client such as a session ID. Still, when i close the browser and open it again, then log req.session, i still get the user id that i previously saved in the session. I was wondering how does express know that it is the same client. If someone could clearify this to me, it would be great.
Here is how i set the session:
app.use(
session({
secret: "This is a secret",
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
},
store: store,
resave: true,
saveUninitialized: true
})
);

express-session Changes the session when the browser is closed

Server on express (4.16.3), with it the express-session (1.15.6) module works.
Code:
// ...
app.use(session({
secret: 'mySecret',
resave: false,
saveUninitialized: true,
store: new MongoDBStore({
uri: 'my-url',
collection: 'sessions'
})
}))
// ...
The essence of the problem: I open the Yandex browser - assign a session, then close it and when I reopen it - a new session. The matter is that authorization is tied to sessions.
The problem is observed in the Yandex browser, microsoft EDGE and in all mobile browsers, while in chrome and opera works correctly.
Help solve the problem or maybe something can replace the module express-sessions
This is happening because your browser default expire the cookie when the browser is closed. In order to fix you can add cookie:{ maxAge: 60000} to your session.
app.use(session({
secret: 'mySecret',
resave: false,
cookie:{ maxAge: 60000},
saveUninitialized: true,
store: new MongoDBStore({
uri: 'my-url',
collection: 'sessions'
})
if you want to make the cookie to not expire, the best way is to set a large number.
// this will it expire in 200 years
cookie: { maxAge: 9000000000000}
or a very far future date in expire property.
// this will expire in year 9999
cookie: {expires: new Date(253402300000000)}

Resources