ES6 module import import does not work with Connect-flash

Seeking assistance with setting up connect-flash for my nodejs express app. My goal is to display a flashed message when users visit specific pages. Utilizing ES6 package module type in this project, my code snippet is as follows. No errors are logged in the console, yet no flashed message appears on visiting the /privacy-policy route.

// Package Imports 
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 contactRoutes from './routes/contact.js';

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

// App Initialization 
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')))

// Session Configuration
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', contactRoutes)

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')
})

Questioning the approach to importing connect-flash with ES6 syntax. What steps can be taken to enable connect-flash functionality? Given the limitation on using import rather than require syntax due to other modules utilized in the application, how else could dynamic messages be displayed upon user redirection?

Your guidance is highly appreciated.

Answer №1

You've successfully brought it into your project. How do you intend to display the message? I typically utilize 'express-messages' and integrate it into my code like so:

import messages from 'express-messages';

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

To then showcase it, I follow the ejs example provided at https://www.npmjs.com/package/express-messages

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch between playing and pausing the mp3 audio in the Next application by using the toggle

I am currently working on my website and I have been trying to add a button to the bottom of the page that can play or pause a song using useSound library. The song starts playing when I click it for the first time, however, I am facing difficulty in stopp ...

Angular 2 release candidate 3 encounters issues with unfulfilled dependencies

Having encountered an issue with npm, specifically related to dependencies while using packages.json from the official Angular2 site's quick start guide. Yesterday everything was functioning correctly, but today I am facing difficulties as npm is unab ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

How can the .pre() middleware function in Mongoose be utilized?

I'm curious about the use cases for mongoose .pre('validate') and .pre('save'). I understand their functionality, but I'm struggling to think of specific scenarios where I would need to utilize them. Can't all necessary a ...

What causes the variation in output results between axios and express when using dot notation?

A geo tool application is in the works, built with reactjs. The concept involves users submitting a city name which then triggers a post request. This request searches through a city list.JSON file to find the corresponding city and returns its geolocation ...

If values are not provided during an update, they will be automatically set as null in the database

I am looking to update certain keys and values in my database. Currently, I have populated fields such as firstname, lastname, and now I wish to add profile pictures, contact numbers, etc. However, when I use the update method, the fields that are already ...

Adding custom styles to an unidentified child element in React using Material-UI

When the function below is executed in a loop, I need to include styles for the icon which will be passed as an argument to the function. The icon element will be an unspecified React Material-UI Icon component. const renderStyledCard = (lightMode, headi ...

Request body is null if accept-encoding is set to 'gzip, deflate'

I'm struggling to capture data from a webhook sent by a third-party source. Despite verifying that the content-length is greater than 0, inspecting req.body only returns {}. The webhook is directed towards the route '/v2/wtevr/report/wtevr'. ...

Unable to generate a vertical navigation bar

When attempting to create a vertical menu, the final result doesn't align as expected. https://i.stack.imgur.com/2ok47.jpg This is the current code being used: $("#example-one").append("<li id='magic-line'></li>") ...

AngularJS faces issue with view not reflecting changes made to model

A web-based game I am developing lets players bid on cards and trade them with one another. The technology stack for this application includes Node, Express, MongoDB, and Angular. The player avatars and names, along with their connection status, are displ ...

Ways to retrieve or access data from another collection in Mongoose

I am looking to retrieve the collection of restaurantOffer data when querying restaurant data. My database Model is as follows Restaurant.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const restaurantSchema = new Sc ...

Exploring the proper syntax of the reduce() method in JavaScript

Here are two codes that can be executed from any browser. Code1: let prices = [1, 2, 3, 4, 5]; let result = prices.reduce( (x,y)=>{x+y} ); // Reduces data from x to y. console.log(result); Code2: let prices = [1, 2, 3, 4, 5]; let result = prices.red ...

Calculate the sum of values in a JSON array response

I recently received a JSON string as part of an API response, and it has the following structure: { "legend_size": 1, "data": { "series": [ "2013-05-01", "2013-05-02" ], "values": { "Sign Up": { "2013-05-05": 10, ...

How to use the Enter key to submit a form in react.js with the help of "@material-ui/core/Button"

Here is the form I have created using the render method for user sign-in. <form onSubmit={this.handleSubmit}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" varia ...

"Utilize the req and res objects within your Passport JS strategy for seamless

I am currently developing an app and I would like to offer my users the option to connect with their Spotify accounts. I have successfully implemented this feature using the Passport JS Spotify strategy. However, I now face a new challenge - I want users t ...

Could someone provide an explanation for the meaning of the phrase "class User extends Model<UserAttribute UserCreationAttribute>"?

View Image of the Issue I am puzzled by why we are utilizing both UserCreationAttribute and UserAttribute in that specific arrow, especially when UserCreationAttribute is created by omitting one field from UserAttribute. Can someone please clarify this fo ...

What is the process for transferring information from a Microsoft Teams personal tab to a Microsoft Teams bot?

Is it feasible to share data such as strings or JSON objects from custom tab browsers to a Teams bot's conversation without utilizing the Graph API by leveraging any SDK functionality? ...

Error: Unable to locate font in the VueJS build

Within my config/index.js file, I have the following setup: ... build: { index: path.resolve(__dirname, 'dist/client.html'), assetsRoot: path.resolve(__dirname, 'dist'), assetsSubDirectory: 'static', assetsPub ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...