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:
xxxxxxxxxx
1
npm install express-mysql-session express-session
xxxxxxxxxx
1
const express = require('express');
2
const session = require('express-session');
3
const MySQLStore = require('express-mysql-session')(session);
4
5
const app = express();
6
7
const options = { // setting connection options
8
host: 'localhost',
9
user: 'root',
10
password: 'password',
11
database: 'my_database',
12
};
13
14
const sessionStore = new MySQLStore(options);
15
16
app.use(
17
session({
18
secret: 'cookie_secret',
19
resave: false,
20
saveUninitialized: false,
21
store: sessionStore, // assigning sessionStore to the session
22
})
23
);
If you already have a MySQL connection, you can use it to create a sessionStore.
xxxxxxxxxx
1
const mysql = require('mysql');
2
const session = require('express-session');
3
const MySQLStore = require('express-mysql-session')(session);
4
5
const options = { // setting connection options
6
host: 'localhost',
7
user: 'root',
8
password: 'password',
9
database: 'my_database',
10
};
11
12
const connection = mysql.createConnection(options);
13
const sessionStore = new MySQLStore({}, connection);
14
15
app.use(
16
session({
17
secret: 'cookie_secret',
18
resave: false,
19
saveUninitialized: false,
20
store: sessionStore, // assigning sessionStore to the session
21
})
22
);