Languages
[Edit]
EN

Node.js / Express.js - how to store session in MySQL database

0 points
Created by:
Dirask Admin - MR
1340

In this article, we would like to show you how to store session data in MySQL database using express-mysql-session module. 

Sessions stored in MySQL database - HeidiSQL
Sessions stored in MySQL database - HeidiSQL

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
    })
);

Node.js / Express.js - session management

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join