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:
xxxxxxxxxx
1
app.get('/path/to/endpoint', (req, res) => {
2
const sessionId = req.session.id;
3
// ...
4
});
or:
xxxxxxxxxx
1
app.get('/path/to/endpoint', (req, res) => {
2
const sessionId = req.sessionID;
3
// ...
4
});
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.
xxxxxxxxxx
1
const express = require('express'); // npm install express
2
const session = require('express-session'); // npm install express-session
3
4
const app = express();
5
6
app.use(
7
session({
8
secret: 'session-secret-here',
9
resave: false,
10
saveUninitialized: true
11
})
12
);
13
14
app.get('/path/to/endpoint', (req, res) => {
15
const sessionId = req.session.id;
16
res.send(`Session ID: ${sessionId}`);
17
});
18
19
app.listen(8080, () => console.log('Server started on port 8080.'));