code to extend the session expiry in express nodejs
Extending session expiry in an Express app can be achieved by updating the session's expiration time each time the user makes a request. Here’s how you can implement this:
-
Using Express-Session Middleware: This approach is suitable if you are using traditional session management with express-session.
-
Using JWT: If you are using JWT for session management, you can issue a new token with an extended expiry time each time the user makes a request.
Using Express-Session Middleware
First, you need to set up the express-session middleware:
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 30 * 60 * 1000 // Initial session expiration time (30 minutes)
}
}));
// Middleware to extend session expiry
app.use((req, res, next) => {
if (req.session) {
req.session.cookie.maxAge = 30 * 60 * 1000; // Extend session by 30 minutes
}
next();
});
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`Number of views: ${req.session.views}`);
} else {
req.session.views = 1;
res.send('Welcome to the session demo. Refresh!');
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Using JWT
If you're using JWT, you will need to issue a new token with an extended expiry time each time the user makes a request:
- Setup JWT Middleware:
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const app = express();
const SECRET_KEY = 'your-secret-key';
app.use(bodyParser.json());
function generateToken(user) {
return jwt.sign(user, SECRET_KEY, { expiresIn: '30m' }); // Token expires in 30 minutes
}
function verifyToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.sendStatus(403);
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
// Extend token expiry middleware
app.use((req, res, next) => {
const token = req.headers['authorization'];
if (token) {
jwt.verify(token, SECRET_KEY, (err, user) => {
if (!err) {
const newToken = generateToken({ id: user.id, username: user.username });
res.setHeader('Authorization', newToken);
}
});
}
next();
});
app.post('/login', (req, res) => {
const user = { id: 1, username: 'test' }; // Authenticate user
const token = generateToken(user);
res.json({ token });
});
app.get('/protected', verifyToken, (req, res) => {
res.send(`Hello ${req.user.username}`);
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Explanation
-
Express-Session Approach:
- The
maxAge
property in the session cookie configuration sets the initial session expiration time. - The middleware checks if a session exists and then updates the session's
maxAge
property, effectively extending the session expiry time on each request.
- The
-
JWT Approach:
generateToken
function creates a JWT with a specified expiry time.verifyToken
middleware verifies the token and attaches the user information to the request object.- Middleware for extending the token expiry verifies the current token and, if valid, issues a new token with an extended expiry time, setting it in the
Authorization
header.
Published on: Jun 12, 2024, 04:47 AM