Dino Geek, try to help you

How to work with sessions using Express.js?


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.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use