The persistence of req.session in express-session seems to be unreliable

I am facing an issue with my current code implementation. Here is the snippet:

var express = require('express');
var cookieParser = require('cookie-parser');
var http = require('http')
var app = express();
app.use(cookieParser());
var session = require('express-session');
app.use(session({
    resave: false,
    saveUninitialized: true,
    secret: 'sdlfjljrowuroweu',
    cookie: { secure: true }
}));

app.get('/test', test);
function test(req, res) {
    var sess = req.session;
    console.log('before', sess);
    if (sess.views) {
        sess.views++
        req.session.save();
        res.setHeader('Content-Type', 'text/html')
        res.write('<p>views: ' + sess.views + '</p>')
        res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
        res.end();
    } else {
        sess.views = 1;
        req.session.save();
        res.end('welcome to the session demo. refresh!')
    }
    console.log('after', sess);
    return;
}

var server = http.createServer(app);
server.listen(8181);

Upon reloading the page, I am consistently receiving the view count as 0 message.

Whenever I check the console, it displays the following information each time:

before { cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true } }
after { cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true },
  views: 1 }

It appears that the data is not getting saved at all.

Answer №1

Modify the cookie setting from { secure: true } to { secure: false }

By toggling the secure flag, you can determine whether the cookie is assigned only on HTTPS connections.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty configuring the node.js environment

Currently on Windows 7, I've been attempting to set the environment variable using SET NODE_ENV="development" in the command prompt. However, this method has not been successful for me. In addition, within npm scripts, I have tried setting the environ ...

building responsive servers within Gulp using connect

Can I validate the availability of a server port before creating it using Gulp? Currently, this is my approach: /** * Start LiveReload Server */ gulp.task('connect', function() { var connect = require('connect'), app = ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Different ways to integrate a sqlite3 database into an ejs file using node.js?

I have successfully connected to my sqlite3 database using node.js. Now, I am looking to utilize the data from the records in a separate ejs file called index.ejs. Does anyone have any insights on how to achieve this? Here is the relevant code snippet: // ...

Is there a way to differentiate between a browser application running on a local development server and an online staging server?

Is there a way to conditionally call a component only on the staging server and not on the local machine in Vue.js? <save-drafts-timer v-if="!environment === 'development'" /> ... data () { return { environment ...

The presence of fsevents (imported by chokidar) in npm shrinkwrap leads to build errors on Windows operating system

On my Windows x64 environment, the fsevents library is causing issues during npm install. This problem stems from it being listed in the shrinkwrap due to its dependency on chokidar, which is only OSX compatible. Our Linux-based production environment is n ...

Having trouble transmitting data with axios between React frontend and Node.js backend

My current challenge involves using axios to communicate with the back-end. The code structure seems to be causing an issue because when I attempt to access req.body in the back-end, it returns undefined. Here is a snippet of my front-end code: const respo ...

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...

When executing code in React JS, I encountered no errors, but the output did not match my expectations

I am facing a challenge with running the Hello World program in React JS using webpack. Attached below is the project structure for reference: https://i.stack.imgur.com/tQXeK.png Upon executing the npm run dev command in the CLI, the browser launches bu ...

The art of transforming properties into boolean values (in-depth)

I need to convert all types to either boolean or object type CastDeep<T, K = boolean> = { [P in keyof T]: K extends K[] ? K[] : T[P] extends ReadonlyArray<K> ? ReadonlyArray<CastDeep<K>> : CastDeep<T[P]> ...

Guide on setting a cookie on ".localhost" using an express/node application in order to make it accessible from "something.localhost"

I have a node/express application running on www.localhost:1234. I am attempting to set an httponly cookie from express with the domain ".localhost" so that I can access it on subdomains like "something.localhost:1234" or "something.localhost:1234". Howeve ...

What is the best way to send an authorization bearer token to a Lambda function that is not an authorizer through API

I'm working with a node lambda function and looking to decode and access the payload of a jwt. My approach involved setting up a get method with lambda proxy integration enabled, passing only the authorization bearer-token to the endpoint. However, I ...

I am having trouble with the `electron` package as `require("electron").app` is showing as undefined. I have just installed new npm

Just yesterday, I was working flawlessly on Electron. But today, when I tried to work on it again, I encountered a major issue where Electron was not functioning at all. To troubleshoot, I deleted the node_modules folder and performed a fresh npm install. ...

Managing dependencies with Yarn or npm

While experimenting with remix and mui v5, I encountered some issues. When using npm and running npm run dev, I received the following error: Error: Directory import '.../playground/remix-mui-dev/node_modules/@mui/material/styles' is not supporte ...

The Node.js server continues to stream data even after the client has disconnected

I recently set up a small Node.js + express server with a dummy download method in place: app.get("/download",function(req,res) { res.set('Content-Type', 'application/octet-stream'); res.set('Content-Length', 1000000 ...

Only the main page is accessible quickly through Express

Currently, I am delving into learning Express and leveraging FS to load my HTML Page. My research on this topic only led me to references of using ASP.NET instead of Express. Here is a snippet from my Server.js file: var express = require('express&a ...

What's the best way to set up multiple NestJS providers using information from a JSON file?

Recently diving into NestJS, I am in the process of building an application following the MVC architecture with multiple modules including: Project | +-- App.Controller +-- App.Service +-- App.Module | +-- SubModule1 | | | +-- SubModule1.C ...

Unable to Delete Record Using Jquery and Express in 'DELETE' Request

While working on my api using node/express and jquery, I encountered an issue where my DELETE requests are not functioning as expected. JQUERY: $('.formula-body').on('click', function (e) { if (e.target.className == 'fa-trash- ...

Tips for organizing your NodeJS application into separate modules

After gaining some knowledge about NodeJS, I am now eager to develop a large enterprise application using it. However, I am uncertain about how to properly structure the project. Having experience with languages like PHP and Java, my initial thought is to ...

Error: Module Not Found in Node.js

Hello everyone, I'm a newcomer to the world of JS and Node.js and I'm facing some issues while trying to set up a webdriverio project using cucumber and PageObject. Whenever I attempt to run a test, I encounter this error message: ERROR: Cannot ...