Question:
How to use/set up Node Express sessions?

Problem:

I've been playing with Express sessions and can't get session variables to stick between routes. I made a smaller example of what I am doing. What more do I need to add to get the req.session.user to log true on both the "/login" and "/" endpoints? I've tried same port (no change) I've tried using connect-sqlite3 (no change).


Backend Express server:


const express = require("express");

const session = require("express-session");

const cors = require("cors");


const app = express();

app.use(cors());


app.use(session({

    secret: "cookie",

    resave: true,

    saveUninitialized: true,

}));


app.get("/login", (req, res) => {

    req.session.user = true

    console.log(req.session.user)

    res.status(200).json({message: "Home page", session: req.session})

})


app.get("/", (req, res) => {

    console.log(req.session.user)

    res.status(200).json({message: "Home page", session: req.session})

})


app.listen(3000, () => {

    console.log("\n *** Server live on port 3000 *** \n");

});


Front-end making fetch calls:


fetch("http://localhost:3000/login")

.then(res => res.json())

.then(data => {

    console.log(data.session)

    fetch("http://localhost:3000")

    .then(res => res.json())

    .then(data => {

        console.log(data.session)

    })

    .catch(error => {

        console.log(error)

    })

})

.catch(error => {

    console.log(error)

})


The logs for the front end and backend show:

cookie: {...}, user: true: cookie: {...} (no user)


Solution:

Fetch takes two arguments, the second of which is optional and is an object which specifies your >options.


One of the options is >credentials and by default it is set to same-origin.


When it is set to same-origin, fetch will not send cookies to cross-origin URLs and it will not set cookies from cross-origin URLs.


express-session uses cookies to track which session belongs to which browsers.

You need to change the option to include.


fetch("http://localhost:3000", { credentials: "include" })


This will have the side effect of making the request >preflighted and require that you >change your server-side CORS handling to allow credentials.


Suggested blogs:

>How to use useQuasar() returns undefined in pinia store file in VueJS?

>How to watch for event changes on a tailwind listbox component with Vuejs?

>How to pass input value to vue component?

>How to change the layout depending on values in the store?

>How can I show 3 items per row in Vuejs?

>What makes index.html have such kind of name in Django?

>Fix Module Not Found Error in Django

>AWS API Gateway: Ways to do REST API Versioning



Ritu Singh

Ritu Singh

Submit
0 Answers