DEV Community

Code_Regina
Code_Regina

Posted on

|Express| Session

                  -Introduction to Sessions 
                  -Express Session
Enter fullscreen mode Exit fullscreen mode

Introduction to Sessions

https://www.npmjs.com/package/express-session

at the terminal


npm install express-session

Enter fullscreen mode Exit fullscreen mode

Sessions are server-side data storage that is used to make HTTP stateful. Instead of storing data using cookies, data is stored on the server-side and then send the browser a cookie that is used to retrieve the data.

HTTP is a stateless protocol, therefore cookies and sessions are used to make HTTP stateful.

Express Session


const express = require('express'); 
const app = express(); 
const session = require('express-session'); 

app.use(session({ secret: 'thisisthesecret' })); 

app.get('/viewcount', (req, res) => {
  if (req.session.count) {
      req.session.count += 1; 
  } else {
      req.session.count = 1;
}
  res.send(`You have viewed the page ${req.session.count} times`)
})

app.listen(3000, () => {
   console.log('Listening on port 3000'); 
})

Enter fullscreen mode Exit fullscreen mode

Alt Text

Top comments (0)