EN
Express.js - get current session id
3
points
In this article, we would like to show you how to get current session id using Express.js.
Quick solution:
app.get('/path/to/endpoint', (req, res) => {
const sessionId = req.session.id;
// ...
});
or:
app.get('/path/to/endpoint', (req, res) => {
const sessionId = req.sessionID;
// ...
});
Practical example
In this example, we present how to get current session id using req.session.id and send it as a response of the HTTP GET request.
const express = require('express'); // npm install express
const session = require('express-session'); // npm install express-session
const app = express();
app.use(
session({
secret: 'session-secret-here',
resave: false,
saveUninitialized: true
})
);
app.get('/path/to/endpoint', (req, res) => {
const sessionId = req.session.id;
res.send(`Session ID: ${sessionId}`);
});
app.listen(8080, () => console.log('Server started on port 8080.'));