Languages
[Edit]
EN

Express.js - how to store session in MySQL database

0 points
Created by:
Dollie-Rutledge
806

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

Alternative titles

  1. Express-session - how to store session in MySQL database
  2. express-mysql-session
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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