Connect-flash not worked when imported via ES6 module import

280 views Asked by At

I'm trying to setup connect-flash for my nodejs express application. I'd like for a message to be flashed when a user goes to certain pages. I'm using ES6 package type module for this application. My code is below. No error is logged in console, but no flashed message appears upon going to my /privacy-policy route.

// Import modules 
import express from 'express';
import path from 'path';
import ejsMate from 'ejs-mate';
import session from 'express-session';
import flash from 'connect-flash';
import methodOverride from 'method-override';
import { fileURLToPath } from 'url';

import mainRoute from './routes/main.js';
import contactRotues from './routes/contact.js';

// Setup path 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Initialize app 
const app = express();

app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))

app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))

// Setup session 
const sessionConfig = {
    secret: 'thisshouldbeabettersecret!',
    resave: false,
    saveUninitialized: true,
    cookie: {
        httpOnly: true,
        expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
        maxAge: 1000 * 60 * 60 * 24 * 7
    }
}

app.use(session(sessionConfig))
app.use(flash());

// Routes 
app.use('/', mainRoute);
app.use('/contact', contactRotues)

app.get('/privacy-policy', (req, res) => {
    req.flash('test message', 'success')
    res.render('privacy')
});

app.get('/terms-of-service', (req, res) => {
    res.render('terms')
});

app.all('*', (req, res, next) => {
    next(new ExpressError('Page Not Found', 404))
})

app.use((err, req, res, next) => {
    const { statusCode = 500 } = err;
    if (!err.message) err.message = 'Oh No, Something Went Wrong!'
    res.status(statusCode).render('error', { err })
})

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

Is there an error in how I'm importing connect-flash? How can I get connect-flash to work? I need to import it with ES6 import syntax rather than require syntax since my application is utilizing a necessary module that must be imported with ES6 module syntax.

If it's impossible to import connect-flash with ES6 import syntax, how else could I dynamically display a message to the user on a page they're redirected to?

Thank you.

1

There are 1 answers

0
Tee_Dub On

You've imported it correctly. How do you plan to render the message? I use 'express-messages' and add to code like this:

import messages from 'express-messages';

app.use((req, res, next) => {
  res.locals.messages = messages(req, res);
  next();
});

Then render using the ejs sample here https://www.npmjs.com/package/express-messages