To manage sessions in Node.js, you will typically need to use Express and a middleware called express-session. Here is a simple way to do it:
```
// Require necessary dependencies
const express = require(‘express’);
const session = require(‘express-session’);
// Initialize Express and middleware
const app = express();
app.use(session({
secret: ‘my secret key’,
resave: false,
saveUninitialized: false,
cookie: { secure: false }
}));
// Handling session
app.get(‘/’, (req, res) => {
// Check if there’s a session
if(req.session.views) {
req.session.views++;
res.send(`You visited this page ${req.session.views} times.`);
} else {
req.session.views = 1;
res.send(‘Welcome to this website. Refresh the page!’);
}
});
// Listen on port 5000
app.listen(5000, () => {
console.log(‘App is listening on port 5000’)
});
```
In the code above, the session allows you to persist the session data between HTTP requests. It needs a secret string that is used to sign the session ID cookie. The `resave` and `saveUninitialized` options are used to decide when to save the session in the store. And `cookie` is used to configure the session cookie.
Every time a user visits the page, the number of views is incremented and stored within the session. There’s no need for manual persistence like writing to databases or files.
Remember always to add the session middleware at the very top of your file to ensure it works properly.
It’s also worth mentioning that in production, you should not store session data in memory as it can lead to memory leaks and does not scale beyond a single process. You should use a session store such as connect-redis or session-file-store.