Express-session on two servers

I’ve been trying to use express-session on two local servers.

The first server is for manipulating the database and the second is for loading pages. I want to save some data in the session from the first server and use it in the second server.

Here’s the code of the first API

require("dotenv").config();

const express = require('express');
const mysql = require("mysql");
const crypto = require("crypto");
const cors = require("cors");

const apiApp = express();

apiApp.use(express.json());
apiApp.use(cors());

const pool = mysql.createPool({
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  host: "localhost"
});

var algorithm = 'aes256'; // algorithm
var key = 'password';

apiApp.post('/api/Connexion', (req, res) => {

  let cipheriv = crypto.createCipher(algorithm, key);  
  let encryptedPassword = cipheriv.update(req.body.motDePasse, 'utf8', 'hex') + cipheriv.final('hex');

  var data = [req.body.courriel, encryptedPassword];

  const query = "SELECT * FROM utilisateurs WHERE courriel=? AND motDePasse=?";
  pool.query(query, data, (error, results) => {
    if (results[0] && !error) {
      res.send(true);
      req.session.courriel = req.body.courriel;
    } else {
      res.send(false);
    }
  });
});

module.exports = apiApp;

And the second

require("dotenv").config();

const express = require('express');
const cors = require("cors");
const path = require("path");

const coreApp = express();

coreApp.use(express.json());
coreApp.use(cors());

let dir = path.resolve(__dirname, '..', '..') + '/'
coreApp.use(express.static(dir));

coreApp.get('/connexion', (req, res) => {
    if (req.session != undefined) {
        console.log(req.session.courriel);
    }
    res.sendFile(dir + "index.html");
});

coreApp.get('/application', (req, res) => {
    res.sendFile(dir + "application.html");
});

coreApp.get('/:a', (req, res) => {
    res.redirect("/");
});

module.exports = coreApp;

So, I am trying to set the session variable at line 64 of the first code and use it at line 17 of the second code.

How can I do it ? Thanks !

Answer

You can share session data between servers if you use a shared database as the session store for express-session, often redis, but any database can work as long as both servers access the same database for express-session storage and express-session is configured properly.

There are express-session storage providers for dozens of databases, including express-mysql-session that works with the database that you’re already using.