Express-session is failing to return a value in spite of my explicit declaration of the session

I've been working on my website for quite some time and everything was smooth sailing, until now.

Here's the issue: after a user logs in, a session cookie named "user" is created to store their email. Upon console logging the cookie right after initialization in the login post request, it displays the correct data. However, when I navigate to another route like the home route, the cookie mysteriously becomes undefined.

In the login post route, Firebase API is utilized for authentication:

// Login POST Route
router.post('/login', (req, res) => {
    // Firebase authentication service
    firebase_user.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(data => {
        // Cookie Init
        req.session.user = req.body.email;
        console.log(req.session.user); // The cookie value appears as intended here
    }).catch(err => {
        res.send({"error": err.message});
    });
});

Now, let's take a look at the home route:

router.get('/home', (req, res) => {
    // Check if Session Cookie Exists
    if (req.session.user) {
        res.render('home.ejs');
    } else {
        res.redirect('/login');
        console.log(req.session.user); // Despite initializing the cookie correctly, it shows 'undefined' here
    }
});

Middleware setup:

app.use(bodyParser.json());
app.use(morgan('combined'));
app.set('view engine', 'ejs');
app.use(express.static('./public'))
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({secret:"Testasl",resave:false,saveUninitialized:true,cookie:{secure:!true}}));

// Routes
app.use(routes);

Let's examine how data is sent to the login method using Axios and Vue:

var urlLog = 'http://localhost:3000/login';

new Vue({
    el: '#main',
    data: {
        email: '',
        password: '',
        showForm: true,
        showPreloader: false,
        errorMessage: '',
        errorShow: false

    },
    methods: {
        submitForm: function() {
            // Form validation
            if (this.email!='' && this.password!=''){

                // Display Preloader
                this.showForm=false;
                this.showPreloader=true;

                // Ajax Post Request
                axios.post(urlLog, {
                    email: this.email,
                    password: this.password
                }).then(res => {
                    if (res.error){
                        // Show form
                        this.showForm=true;
                        this.showPreloader=false;

                        // Display Error
                        this.errorShow = true;
                        this.errorMessage = res.error;
                    } else {
                        // do nothing
                    }
                // Server Side error
                }).catch(err => {
                    console.log(err);
                });
            } else {
                this.errorShow = true;
                this.errorMessage = 'All fields are necessary...';   
            }
        }
    }
});

Any insights on why this behavior is occurring?

**** EDITED ****

UPDATE: As I tinkered with cookies, specifically using the cookie-parser module to initialize one, an error popped up:

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:491:11)
    at ServerResponse.setHeader (_http_outgoing.js:498:3)
    at ServerResponse.header (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:767:10)
    at ServerResponse.append (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:728:15)
    at ServerResponse.res.cookie (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:853:8)
    at router.get (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\bin\routes.js:74:9)
    at Layer.handle [as handle_request] (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\layer.js:95:5)

The cookie creation was done like this:

// Login GET Route
router.get('/login', (req, res) => {
    res.render('log_in.ejs');
    res.cookie('idk', 'idksj');
    console.log(req.cookies);
});

Answer №1

The error you're encountering is due to trying to set a header after the headers have already been sent. In your scenario, the issue arises from setting the cookie header after the response has been completed:

// Login GET Route
router.get('/login', (req, res) => {
    res.render('log_in.ejs'); // completes the response
    res.cookie('idk', 'idksj'); // attempts to set a cookie header
    console.log(req.cookies);
});

To resolve this problem, simply switch the order of these two lines:

// Login GET Route
router.get('/login', (req, res) => {
    res.cookie('idk', 'idksj');
    res.render('log_in.ejs');
    console.log(req.cookies);
});

It's advisable to perform this action after validating the login credentials, which seems to be missing in the provided code block.

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

Designing templates for websites and applications using node.js

Simplified Question: As I delve into improving my skills with node.js, I'm exploring the concept of templating. How would using node to serve one HTML file and loading page-specific information through AJAX/sockets impact performance and design princ ...

Is the state variable not being properly set by using React's setState within the useCallback() hook?

Within a React FunctionComponent, I have code that follows this pattern: const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray, someFunction }) => { const [someStateObjVar, setSomeStateObjVar] = React.useState({}); const [ ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

The functionality of $(selector).css() seems to be malfunctioning

I currently have an html div element stored in a variable var rows = ""; rows += "<div>1111 : Hi there</div>"; Despite multiple attempts, I have failed to add a background color to this div using the following methods: 1. $(rows).css({&apos ...

Skipping the validation of a variable in a return statement with Angular and Javascript

Is there a way to exclude level a.3 from the return in the completion form if a.3 is undefined? scope.isValid = function() { return a.1 && a.2 && a.3; }; ng-disabled="!isValid()" ...

How to ensure router state synchronization in a custom Vue library component with <router-link>?

I'm currently in the process of developing a reusable navigation component that utilizes vue-router <router-link> for navigation. The unique aspect of this component is that the navigation elements change styles based on active links. When I im ...

Ways to troubleshoot JavaScript following an AJAX request?

My webpage is structured into three separate files. The index.html file contains a navigation bar, a content box, and a footer within 3 divs. Additionally, there are two other .html files with different content that should load upon clicking specific links ...

Combining AddClass and RemoveClass Functions in Mootools Event Handlers

I am currently in the process of creating a CSS animation, and one aspect involves changing the class name of the body at specific intervals. Since I am relatively new to Mootools (and JavaScript in general), my approach has been to add/remove classes to ...

The variable in Vue.js is failing to update, resulting in a "variable is not defined" error

I've been attempting to display the updated value of the totalQuestions variable in the HTML, but I keep encountering the following error. Can someone point out where I went wrong? HTML <label><span class="red-text">Question No: </spa ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

Masking input text to allow numbers only using either javascript or jquery

I have experience with javascript and jquery. My goal is to create a masking template for <input type="text"> This template should only accept numbers and automatically format the input with dashes after every two numbers typed. The desi ...

When the onload event is triggered, the jscript function called var data is loaded, without any interruption in

I encountered an issue while trying to preview an image from a BBCode decoder. The code works fine, but I need the image to be inside an <a> href link, so that people can click on it and get the image source. Additionally, I want to display a message ...

Updating items in a MongoDB object using Mongoose

I need to make changes to an item in my mongodb collection. Within my database, there is a "person" with the following details: { "_id": {Random Object Id}, "property": [{ "model": ["BMW", "Toyota", "Honda"], "color": ["red", "blue", "yellow"], }, { ...

Using promise.then after res.json in Express 4 does not function as expected

I have been working on a project involving an express 4 app that utilizes the mysql and sequelize packages. The Sequelize ORM relies on promises to fetch data from the database. I've encountered an issue when trying to fetch data in the router and sen ...

What is the best way to send a JavaScript variable to PHP for storage in a WordPress database?

I am currently in the process of developing a star rating system within Wordpress and am looking to store the rating data in the Wordpress database. To achieve this, I have saved the star rating PHP code as a template within my Wordpress theme folder. Belo ...

Loading identical items using jQuery Ajax

I have a situation where an ajax request is returning multiple URLs which I am using to create images like: <img URL="1" /> <img URL="1" /> <img URL="2" /> <img URL="1" /> <img URL="3" /> <img URL="2" /> and so on... ...

What is the best way to create a dynamic text area that changes based on a dropdown selection?

I'm trying to create a feature on my form where selecting a retailer from a dropdown menu automatically generates a corresponding link next to the textbox. For example, if someone picks Best Buy, I want a link to bestbuy.com to show up immediately wit ...

What is the best way to extract ABC 12005 from strings like ABC000012005 and ABC0000012005?

My task involves parsing a string with values like ABC000012005,ABC0000012005. The desired output is to extract the prefix and numbers without leading zeros, formatted as ABC 12005, ABC 12005 ...

Difficulty encountered in closing div by clicking the background with the help of jquery

I am facing a challenge with properly closing a div container and restoring it to its original state when I click outside of it. Despite trying various solutions from stackoverflow and extensive internet research, I have been unable to find or come up with ...

How can one adhere to Angular's recommendation of "always using dots with ngModel" while working within isolate scopes?

Currently, I am working on developing an Angular application utilizing Bootstrap. To reduce the impact of Bootstrap on my HTML code, I have implemented two directives specifically for forms: form-control.js module.directive('formControl', func ...