Giter Club home page Giter Club logo

connect-flash's Introduction

connect-flash

The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.

This middleware was extracted from Express 2.x, after Express 3.x removed direct support for the flash. connect-flash brings this functionality back to Express 3.x, as well as any other middleware-compatible framework or application. +1 for radical reusability.


Advertisement
The Complete 2020 Web Development Bootcamp
Become a full-stack web developer with just one course. HTML, CSS, Javascript, Node, React, MongoDB and more!


Install

$ npm install connect-flash

Usage

Express 3.x

Flash messages are stored in the session. First, setup sessions as usual by enabling cookieParser and session middleware. Then, use flash middleware provided by connect-flash.

var flash = require('connect-flash');
var app = express();

app.configure(function() {
  app.use(express.cookieParser('keyboard cat'));
  app.use(express.session({ cookie: { maxAge: 60000 }}));
  app.use(flash());
});

With the flash middleware in place, all requests will have a req.flash() function that can be used for flash messages.

app.get('/flash', function(req, res){
  // Set a flash message by passing the key, followed by the value, to req.flash().
  req.flash('info', 'Flash is back!')
  res.redirect('/');
});

app.get('/', function(req, res){
  // Get an array of flash messages by passing the key to req.flash()
  res.render('index', { messages: req.flash('info') });
});

Examples

For an example using connect-flash in an Express 3.x app, refer to the express3 example.

Tests

$ npm install --dev
$ make test

Build Status

Credits

License

The MIT License

Copyright (c) 2012-2013 Jared Hanson <http://jaredhanson.net/>

connect-flash's People

Contributors

jaredhanson avatar peterwooley avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

connect-flash's Issues

Deprecation Warning: The `util.isArray` API is deprecated. Please use `Array.isArray()` instead.

To the devs of connect-flash,

In my nodejs project, I used connect-flash to display messages like 'Comment created successfully', etc. when I got the following warning:

(node:4588) [DEP0044] DeprecationWarning: The util.isArray API is deprecated. Please use Array.isArray() instead.

The stacktrace tells me it originated from connect-flash\lib\flash.js:67:16 when I used node --trace-deprecation

Kindly change it as soon as possible.

Thank you!

add getFlash and setFlash methods

Right now, the only way to get AND set the flash parameters is through req.flash().

However, this can lead to unexpected situations, imagine a case where you call req.flash('msg', obj.with.string); but somehow, obj.with.string equals null, zero or empty string.

This will flush the complete msg buffer and you'll wonder where your flash message went. I therefore suggest to seperate the logic of adding flashMessages and getting/cleaning them!

Using app.configure in example code

In the example code we are using

app.configure(function() {
  app.use(express.cookieParser('keyboard cat'));
  app.use(express.session({ cookie: { maxAge: 60000 }}));
  app.use(flash());
});

But app.configure is removed in Express 4.0.

res.locals

Is there a good way to pass req.flash to res.locals?

I want to have access to flash in my views and do not want to pass it every time on res.render.

Req.flash() automatic set session when it's not required to do so.

When in read-only scenario. Which flash is not yet existed. running req.flash('name') will set req.session.flash to {} which will prevent caching.

Solution:

  • Make sure req.session.flash is set only when req.flash() have 2 args.
  • Make sure fetching flash data return empty array if req.session.flash does not exists

Return all flash messages as array if key isn't passed

If req.flash() is called like that without any arguments, it should return an array of all the messages regardless of their key. For example

[
  { type: 'info', message: 'message 1' },
  { type: 'error', message: 'message 2' },
  { type: 'success', message: 'message 3' },
]

This is so that you are sure you are getting all error messages regardless of key. If you only do req.flash('info/success/error, etc you will miss messages that have been added under a new key. It also makes the templates more complicated. Instead of simply doing

for msg in flash
  <div class='{{ msg.type }}'>{{ msg.message }}</div>

You would have to do

for msg in flash('info')
  <div class='info'>{{ msg }}</div>
for msg in flash('error')
  <div class='error'>{{ msg }}</div>
for msg in flash('success')
  <div class='success'>{{ msg }}</div>

and would have to remember to add to this list when new flash message types are added throughout the application.

If such a change is considered breaking and unacceptable, could it be added as a new method under the flash object, like flash.all()?

Node.js req.flash issues

I'm having issues in returning messages with req.flash()
I'm trying to return a string message to the view instead it's flashing 1.
This is the short code:
return res.render('index', {
error_msg: req.flash('error_msg', 'Not found'),
success_msg: ''
})

about the name

i think "session-flash" is a better name for the package :)

anybody think so too?

Error: req.flash() requires sessions

I get this error when I'm trying to use req.flash in my project, I am using express 4.0.0 where all my node modules installed in Windows PC

res.render('login.ejs', { message: req.flash('loginMessage') });

Kindly do the needful to fix this.

Thanks In Advance :)

req.flash returns empty array

Hi,

I have been using connect-flash for my nodejs server which uses express 4 and it is hosted from localhost:3000.
This works fine when I post with postman, but if I call this server from another server then req.flash() returns an empty array

req.flash() requires sessions

I get this error when I'm trying to to use req.flash. This is my configuration (express 3.4.7):

var flash = require('connect-flash');
var express = require('express');

app.use(express.cookieParser());
app.use(express.session({
  secret: 'sdkfhsdkhfslkdhfhdklvcbjvcblvjew',
  store: new RedisStore()
}));
app.use(flash());

Success & Error Flashes

On a particular page, I want to have a flash for both success and error messages. However, I cannot figure out how to determine which is which in the view template:

request.flash('success', message);
request.flash('error', message);

How to access the message in the view: <%= message %>

if(message.error) {
     // Show error state
} else if(message.success) {
     // Show success state
}

But I'm not seeing any way to do this? Is this possible?

What is the `unsafe` option?

What is the unsafe option and when should it be used?

I looked through the source code and unsafe doesn't seem to make a difference. req.flash in the following is always undefined every time the middleware is called on every Http request, so that test condition will always be false.

function(req, res, next) {
  if (req.flash && safe) { return next(); }
  req.flash = _flash;
  next();
}

Passing an object value to req.flash()

I’m interested in expanding connect-flash to allow passing objects to it. Ideally, I’m looking to do this:

// controller.js

// some other logic happens, then…

// this generates error messages indexed by field name:
var errors = req.validationErrors(true)

if (errors) {
  req.flash('errors', 'Your submission is invalid. See errors below.')
  req.flash(req.validationErrors(true))
  return res.redirect('back')
}

This way, it would be trivial to check for messages.fieldName from my templates like so:

//- template.jade

//- other fields and markup

label(for='fieldName') Field Name:
input(name='fieldName' id='fieldName' class=(messages.fieldName ? 'error' : ''))
if messages.fieldName
  label(for='fieldName').error #{messages.fieldName.msg}

Specifically, I’d like to expand on req.flash() to accept a non-Array object as the second argument or the only argument. Behavior could be as follows:

  1. req.flash('type', object) — Only the object would be registered at req.session.flash.type (i.e. not an array with the passed object as its first item). If an object had already been registered for that type, it would be expanded with the current object’s properties (read: not entirely replaced). If a non-object had already been registered for that type (i.e. req.flash('type', 'A message') followed by req.flash('type', object)), then we would respect the existing array and simply push to it, resulting in req.session.flash.type being equal to [ 'A message', object ].
  2. req.flash(object) — Each key/value pair at the root of the provided object is handled as if it was req.flash(key, value), following existing conventions as well as the new conventions I described above.

I don’t think this would break existing functionality (please correct me if I’m wrong) and it would make more granular error reporting to the user easier to implement.

Is this a contribution you would be interested in, or would you rather it live as a separate project?

Why are flashes always arrays?

Why is it that in order to access:

req.flash('message', 'You forgot to enter something');

I have to do:

req.flash('message')[0];

instead of:

req.flash('message');

?

req.flash() returning different values on same scope

I set a flash value as:
req.flash('error', 'Invalid email or password');

but when i accessing this in appropriate section with console.log, the results are different:

console.log(req.flash('error')); //output: ['Invalid email or password']
console.log(req.flash('error')); // output: []

what is reason? why it is returning different result?

Error: req.flash() requires sessions

Hello

I get the error "Error: req.flash() requires sessions" using connect-flash, I use Express 4.17... I do not understand it seems my setup is correct.
Here is my main.js

const Session = require('express-session');
const redis = require('redis');

let RedisStore = require('connect-redis')(Session)
let redisClient = redis.createClient()

app.use(flash());
app.use(Session({
    store: new RedisStore({ client: redisClient }),
    secret: config.server.secret,
    cookie: {maxAge: Date().now + (60 * 1000 * 30) } ,
    resave: false, 
    saveUninitialized: false
}));

Here is the code of the route where the error come from

const express = require('express'),
    router = express.Router(),
    passport = require('passport');
 
router.get('/',
    require('connect-ensure-login').ensureLoggedOut(),
    (req, res) => {
        res.render('register', {
            user : null,
            errors : {
                username : req.flash('username'), <-- error here
                email : req.flash('email')
            }
        });
    });

Redis is started up

Thanks for your help

Laurent

req.flash return content with brackets ['message']

I'm having a problem with req.flash when I am try to set a flash message inside a function:
I am doing:

req.flash('info', 'Yep all good' );

but then when I am using console.log to display it:
console.log(req.flash('info'));

I get : [ 'Yep all good' ] with brackets.
I do not know what do to fix this. Can someone give me a help. Is that a bug?

Wrong example checking for message

The examples show that this if (message) { is the proper way to check if a message is there, actually this will be true every time, even if no message is set. It seems to work with:

if (message.length !== 0) {

I am not sure, but it seems that message, when empty is an empty object ({}) so checking for it will be true in any case.

res.redirect happening before req.flash

Hi

I am using express 4 and connect-mongo.

I have the following code in a route:

if (doc.pwdResetExpiration < new Date()) {
    req.flash('error', 'Your recovery token has expired, please try again.');
    return res.redirect('/account-recovery');

it can happen that the redirect is processed before the flash message in stored in the session (so it is never flashed to the user). It happens ~20% of the time

The output of console.log(req.flash()) in /account-recovery when repeatedly loading the above route :

{ error: [ 'Your recovery token has expired, please try again.' ] }  ==> it flashed ok
{} ==> the flash was not stored in time
{ error:  ==> it flashed ok again
   [ 'Your recovery token has expired, please try again.',
     'Your recovery token has expired, please try again.' ] }

Is there an easy way to make sure the flash message is stored before executing the redirect ?

Getting a flash message also clears it

It is expected that methods which return data should not have side effects. Currently, if I get data from the flash then that data is cleared:

req.flash('url');
// [ '/users/1']

req.flash('url');
// []

This leads to confusing code:

if (req.flash('url') && req.flash('url').length) {
    // Never gets executed.
    req.flash('url', req.flash('url'));
}

To get around this problem I need to add unnecessary temps to my methods and, worse, unnecessary properties to my methods.

There should be an explicit method to clear items from the flash, and getting them should not have side effects.

flash for node 0.12 and lower version

I'm using node 0.12.5. I cannot get the message in jade views with forms like 'flash.info', am I using it in a wrong way?
What's more, I must add
res.locals.flash = req.flash();
in your flash.js after
req.flash = _flash;
in line 20 and successfully get the message.
What's wrong with me please?

Winston logging support

In Winston we use "warn" as the error type, e.g. logger.warn('something').

In Connect-Flash we use "warning" as the error type, e.g. req.flash('warning', 'something').

Would it be OK with you if I submitted a PR for adding legacy/fallback support so we can use connect-flash with "warn" as an error type?

Connect Flash is not working in Express 4.16.3

I've tried both connect-flash and connect-flash-plus both without any luck with my following simple express app. It is totally non-responsive. Here is my package.json:


{
    "name": "vidjot",
    "version": "1.0.0",
    "main": "index.js",
    "repository": "https://github.com/ahmedmusawir/vidjot.git",
    "license": "MIT",
    "dependencies": {
      "connect-flash": "^0.1.1",
      "connect-flash-plus": "^0.2.1",
      "express": "^4.16.3",
      "express-handlebars": "^3.0.0",
      "express-session": "^1.15.6",
      "method-override": "^3.0.0",
      "mongoose": "^5.2.15"
    }

and here is my index.js and template file.


const express = require('express');
    const exphbs = require('express-handlebars');
    const mongoose = require('mongoose');
    const methodOverride = require('method-override');
    const session = require('express-session');
    const flash = require('connect-flash');

    const app = express();

    //FOLLOWING REPLACES BODY PARSER IN EXPRESS 4+
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    //METHOD OVERRIDE MIDDLEWARE
    app.use(methodOverride('_method'));
    //SESSION MIDDLEWARE
    app.use(
      session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true,
        cookie: { maxAge: 60000 }
      })
    );
    //FLASH MESSEGING MIDDLEWARE
    app.use(flash());

    //GLOBAL VARIABLES
    app.use(function(req, res, next) {
      res.locals.success_msg = req.flash('success_msg');
      console.log(req.flash('success_msg'));
      res.locals.error_msg = req.flash('error_msg');
      res.locals.error = req.flash('error');
      next();
    });

    ...
    ...

    //DELETE NOTE
    app.delete('/notes/:id', async (req, res) => {
      Notes.remove({ _id: req.params.id }).then(() => {
        console.log(req.flash('success_msg'));
        req.flash('succss_msg', 'Note has been Removed');
        res.redirect('/notes');
      });
    });

My template file:

`



{{> _navbar }}

    {{#if succss_msg}}
    <div class="alert alert-success">{{success_msg}}</div>
    {{/if}}

    {{#if error_msg}}
    <div class="alert alert-danger">{{error_msg}}</div>
    {{/if}}

    {{{body}}}

  </div>

</body>

`

Plz let me know what am I doing wrong here ... Thanx in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.