0

I'm trying to initialize a session in my website once a user logs in, but for some reason, once a user successfully logs in, a cookie isn't sent to the browser and a session isn't maintained. When I tried playing with the website's API in Postman, a session was successfully maintained, but in Google browser it isn't.

This is my code for initializing a session:

const express = require('express');
const app = express();
const dotenv = require('dotenv').config();
const session = require('express-session');
const store = session.MemoryStore();
const helmet = require('helmet');
const cors = require('cors');
const cookieParser = require('cookie-parser');

app.enable("trust proxy");
app.use(cookieParser());
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
    resave: false,
    saveUninitialized: true,
    secret: process.env.SESSION_SECRET,
    cookie: {maxAge: 1000*60*60, sameSite: 'none', secure: false},
    store,
}));

Once a user successfully logs in, a 'user' property and an 'authenticated' property get attached to the session object, and for any subsequent request, the server checks if the client is authenticated with the following function:

const checkIfAuthenticated = (req, res, next) => {
    if(req.session.authenticated){
        next();
    } else {
        res.json("Please authenticate yourself!");
    };
};

After a user successfully logs in , a session should successfully be maintained. What actually happens is that once a user logs in successfully and tries to access and modify personal data, they are sent "Please authenticate yourself!", meaning that no session was initialized.

This is my frontend code for logging in (a username and a password re needed):

export async function loginUser(username, password){
    console.log(username, password);
    const res = await fetch('http://localhost:4001/login', {
        method: 'POST',
        body: JSON.stringify({username, password}),
        headers: {
            "Content-Type": "application/json",
          },
    });
    const jsonRes = await res.json();
    return jsonRes;
}

And this is my frontend code for fetching products data (Any request to the products data is first authenticated by the 'checkIfAuthenticated' function written above, and if the user is authenticated, the server sends the products, and if not, the user will be asked to authenticate themself):

export async function getAllProducts(){
    const products = await fetch('http://localhost:4001/products');
    const jsonProducts = await products.json();
    return jsonProducts;
}

What should I change in my code in order for it to work properly?

1 Answers1

1
 fetch('http://localhost:4001/login'

Cross-origin Ajax requests do not support credentials that are stored and automatically sent by the browser (such as cookies) unless you explicitly set the credentials option and allow it in the CORS response from the server.

fetch('http://localhost:4001/login', {
        method: 'POST',
        credentials: 'include'

and

fetch('http://localhost:4001/products', { credentials: 'include' });

and

app.use(cors({ credentials: true }));
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Hello @Quentin, thanks for your response. I tried adding what you recommended to my code, but each time I submit credentials and fetch 'http://localhost:4001/login', I get the following error: **Uncaught runtime errors: ERROR Failed to fetch TypeError: Failed to fetch at loginUser (http://localhost:3000/main.38f30d6e1437d61d705c.hot-update.js:37:21)** – user22019491 Jun 05 '23 at 11:35
  • @user22019491 — That's an unrelated problem with your hot reload server. Kill it, restart it, reload the page from scratch in your browser. – Quentin Jun 05 '23 at 12:11
  • I killed my server and reloaded it, but still no cookie is set in the browser. I tried setting credentials to 'same-origin', but it still doesn't work. I also tried making the requests to 'http://127.0.0.1:4001' rather than to localhost, but it still doesn't work. Do you have any other idea for fixing this? – user22019491 Jun 05 '23 at 19:55