본문 바로가기
TIL: Today I Learned

[TIL] 20201226 Express Session & Flash

by 김알리 2020. 12. 26.

Sessions

  • Sessions are a server-side data store that we use to make HTTP stateful. Instead of storing data using cookies, we store the data on the server-side and then send the browser a cookie that can be used to retrieve the data.
  • It's not very practical or secure to store a lot of data client-side using cookies. This is where sessions come in. 

Express Session

  • install : npm i express-session
  • Example
const session = require('express-session');

app.use(session({secret: 'thisissecret'}));
app.get('/viewcount', (req, res) => {
    if (req.session.count) {
        req.session.count += 1;
        //The information is stored in the JS memory store by default,
        //which is not recommended in production.
    } else {
        req.session.count = 1;
    }
    res.send(`You have viewed this page ${req.session.count} times.`);
})

 

 

 

Flash

  • A place in the session used for storing messages.
  • Messages are written to the flash and cleared after being displayed by the user.
  • Typically used in combination with redirects.
  • Example
app.get('/flash', (req, res) => {
    req.flash('info', 'Flash is back');
    res.redirect('/');
})

app.get('/', (req, res) => {
    res.render('index', {messages: req.flash('info')});
    //second argument : get an array of flash messages by passing the key to req.flash()
    //This message can be used in HTML template now.
})

res.locals 

  • An object that contains response local variables scoped to the request, and therefore available only to the views rendered during that request/response cycle (if any).
  • Example
app.use((req, res, next) => {
    res.locals.messages = req.flash('success');
    next();
})

 

 

 

 

 

 

 

* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.