EN
Express.js - how to store session in MySQL database
0
points
In this article, we would like to show you how to store session data in MySQL database using express-mysql-session
module.
Note:
Data about sessions created using express-session is stored in the MemoryStore instance by default However, this is not advisable, so we can store this data in the MySQL database.
First step is to install express-mysql-session
and express-session
using npm:
npm install express-mysql-session express-session
Practical example
const express = require('express');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const app = express();
const options = { // setting connection options
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database',
};
const sessionStore = new MySQLStore(options);
app.use(
session({
secret: 'cookie_secret',
resave: false,
saveUninitialized: false,
store: sessionStore, // assigning sessionStore to the session
})
);
With an existing MySQL connection
If you already have a MySQL connection, you can use it to create a sessionStore.
const mysql = require('mysql');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const options = { // setting connection options
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database',
};
const connection = mysql.createConnection(options);
const sessionStore = new MySQLStore({}, connection);
app.use(
session({
secret: 'cookie_secret',
resave: false,
saveUninitialized: false,
store: sessionStore, // assigning sessionStore to the session
})
);