mikefreudiger
mikefreudiger

Reputation: 1

Unable to set express-session and have it save across nodejs app

I am unable to save an express-session custom value across the routes of my nodejs API. Even when I revisit the same route, my session attribute is undefined. I'm trying to set req.session.custom_attr = 1; and it will not save outside of the initial request. Can anyone tell me what I'm doing wrong???


//app.js

app.use(session({
    secret: 'my s3cret',
    resave: false,
    saveUninitialized: false
}));

app.use(cors({
    origin: 'http://localhost:3000',
    // credentials: true
}));

//middlewear here:
app.use('/api', api);


// routes in api
// this works and returns custom_attr
router.get(`/setSession`, async (req, res, next) => {
    req.session.custom_attr = 1;
    req.session.save((err) => {
        if (err) {
            console.error(err);
            return res.status(500).send('Error saving session');
        }

        res.json({ "message": `Database set to ${req.session.custom_attr}` });
    });
});

// next api
router.get(`/getSession`, async (req, res, next) => {
    try {
        console.log(JSON.stringify(req.session.custom_attr)); // undefined

        res.json(response);
    } catch (e) {
        res.status(500).json({
            message: 'An unexpected error occured',
            error: e.message
        });
    }
});

Upvotes: 0

Views: 33

Answers (0)

Related Questions