I used both cookie-session and express-session, I also specified maxAge but still, it's no use.
const expressSession = require("cookie-session");
const IN_PROD = process.env.NODE_ENV === "production";
app.use(
expressSession({
name: process.env.SESSION_NAME, //setting custom name
resave: false, // do not store if it never modified
secret: process.env.SESSION_SECRETE, // secrete key which we dont't want expose to client
saveUninitialized: false, //dont save the session which is empty
cookie: {
maxAge: 30 * 24 * 60 * 60 * 1000, //Session liftime
sameSite: true,
secure: IN_PROD, //set true when application is in production mode and false when it is in development mode
},
})
);
Related
I am trying to connect to Redis using typescript and nodejs but I keep getting **
error TS2693: 'RedisStore' only refers to a type, but is being used as a value here.**
let redisCLient = createClient({legacyMode: true});
redisCLient.connect().catch(console.error);
declare module "express-session" {
interface SessionData {
isLoggedIn: boolean;
}
}
// middleware
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cors());
app.use(
session({
secret: "reddit_apples_should_be_next",
resave: false,
saveUninitialized: false,
store: new RedisStore({client: redisCLient}),
})
);
You can do stuff like this
Basic Redis setup
Import statements
const express = require('express');
const session = required('express-session');
const redis = require('redis');
const connectRedis = require('connect-redis');
const app = express();
app.use(express.json());
connection
const RedisStore = connectRedis(session);
const redisClient = redis.createClient(
port: 6379,
host: 'localhost'
});
configure session middleware
app.use(session({
store: new RedisStore({client: redisClient}),
secret: 'mySecret',
saveUninitialized: false,
resave: false,
name:'sessionId',
cookie: {
//secure false for non https request , keep false in production
secure: false,
// if true, prevents client side JS from reading the cookie
httpOnly: true,
//session age in millisec // 30 mins
maxAge: 1000 * 60 * 30
}
}));
I'm using Redis Store to store my sessions since I use a serverless backend, and I'm running into problems to set my cookie.
My frontend and backend currently run on 2 different domains, and this is how I configured my session management:
app.use(json());
app.use(
session({
store: new RedisStore({ client: redisClient }),
secret: options.sessionSecret,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'PROD' ? true : 'auto',
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 7,
sameSite: process.env.NODE_ENV === 'PROD' ? 'none' : 'lax',
},
})
);
As said, the issue occurs when I'm in production, when I'm in development my cookie generates as expected.
Is my session configuration incorrect? Or missing something?
TIA!
As #Brijesh mentioned, we should set a property to trust the proxy:
app.set('trust proxy', 1)
app.use(json());
app.use(
session({
store: new RedisStore({ client: redisClient }),
secret: options.sessionSecret,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'PROD' ? true : 'auto',
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 * 7,
sameSite: process.env.NODE_ENV === 'PROD' ? 'none' : 'lax',
},
})
);
I am having the hardest time sending cookies from my nodejs server to my browser. Below is my index.js (server side) code:
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true
})
);
let port = process.env.PORT;
if (port == null || port == "") {
port = 5000;
}
mongoose.connect(process.env.ATLAS_URI).then(console.log("MongoDB Connection Success")).catch(err => console.log("MongoDB Connection Failed" + err))
app.use(session({
secret: 'random secret',
resave: false,
saveUninitialized: false,
// store: MongoStore.create({ mongoUrl: process.env.ATLAS_URI }),
cookie: {
expires: 7 * 24 * 6 * 60 * 1000,
secure: false,
},
}));
app.use(cookieParser())
app.use(passport.initialize())
app.use(passport.session())
app.use("/auth", auth)
I know a cookie is being created when i authenticate a user because if i uncomment out the store in app.use(session({...}) i see session IDs and cookies in my mongodb. But how can I send it to the browser?
try this config for the session options.
my version of express-session is "^1.17.2"
app.use(session({
name: 'random name',
resave: false,
saveUninitialized: false,
secret: 'random secret',
store: MongoStore.create({
mongoUrl: config.DatabaseUrl,
ttl: 14 * 24 * 60 * 60 // = 14 days. Default
})
}));
if this config does not work, check your passport authenticate function that set session true like the below example :
passport.authenticate('local.register', {session: true}, (err, user): void => {
// When res has an Error
if (err) return res.redirect('/auth/register');
return res.redirect('/');
})(req, res);
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.
Here i am trying to access maxAge and expires inside app.use() and inside app.use() method i have session() and inside session() i am assigning maxAge and expires but it's not assiging the value to cookies.
NOTE: i am accessing maxAge and expires from a property file in real application
var maxAge = 3000;
var expires = 3000;
app.use(session({
secret: 'Test API',
name: "test",
saveUninitialized: true,
resave:false,
rolling: true,
cookie: {
maxAge: maxAge, //undifined,
path: '/',
expires: expires //undifined,
overwrite: false,
activeDuration: 24 * 60 * 60 * 1000,
ephemeral: true
}
}));