In Express.js, you can handle sessions using various libraries. One of the most commonly used is `express-session`.
Here are the steps to work with sessions using `express-session`:
1. Install `express-session`:
`npm install express-session`
1. Import `express-session` into your Express.js project:
```
const session = require(‘express-session’);
```
1. Set up the middleware:
```
app.use(session({
secret: ‘your-secret-key’, //used to sign the session ID cookie.
resave: false, //do not save session if unmodified
saveUninitialized: true, // do not create session until something stored
cookie: { secure: true } // secure:true for https connections else false
}));
```
1. After the middleware is set, you can access the session in your routes. `req.session` object is available in routes.
Example of setting a value in session:
```
app.get(‘/setSession’, function(req, res){
req.session.userDetails = {
username: ‘example’,
email: ‘example@example.com’,
admin: true
};
res.send(‘Session Set’);
});
```
Example of getting a value from the session:
```
app.get(‘/getSession’, function(req, res){
if(req.session.userDetails){
res.send(req.session.userDetails);
}else{
res.send(‘No Session Found’);
}
});
```
Example of destroying a session:
```
app.get(‘/destroySession’, function(req, res){
req.session.destroy(function(err){
if(err){
console.log(err);
}else{
res.send(‘Session Destroyed’);
}
});
});
```
Remember to handle your secret key securely and not expose it.
Also note that you may need to use an additional packet, like “cookie-parser”, if you want extra features of cookies, or “connect-mongo”, “connect-redis” if you want to store sessions in MongoDB, Redis, etc., rather than in memory storage.
It’s also meant to be used with `cookie: { secure: true }` for production (this requires an HTTPS connection). For the development purpose you can set it to false.