Build a Flush Message Middleware with Node.js

Learn how to build a flush messages middleware system with node.js and express.js from scratch

Photo by Octavian Rosca on Unsplash

1.Introduction

In this story, we’ll learn how to build a flush message middleware from scratch with node.js and express.js.

But what is flush messages?

Flush messages are small messages with information that inform the user-client about various cases, such as unsuccessful login, invalid input on a form field etc …

Start by cloning the project repository

2. Install and discover

cd flushMessages/startFlushMessages

Install the dependencies:

npm install

Your directory:

project directory

Our start template have:

An index.js file with a standard express app and sessions. A views folder with one page views/pages/home.ejs and a views/template folder with head.js, footer.ejs, and messages.ejs.

Run the start application:

npm run start

Hit at the browser http://localhost:3000

3. Build the middleware

Create a new file with name flushSystem.js at your root project folder and paste the following code:

The above code exposes a function that returns a middleware, and the middleware is doing the following jobs:

1.Checks if the request object has sessions

// Check for sessions if(!req.session){ throw new Error('flushSystem must have sessions enabled') }

2. Initialize an array to store the flush messages at req.session.messages

// INIT messages array if (!req.session.messages) { req.session.messages = []; }

3. Initialize the res.locals.messages with an array, we use res.locals.messages to send messages array to all views directly from the response object

res.locals An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any).

// INIT THE locals.message res.locals.messages = [];

4. Add a reference to request.locals from response.locals

// add res.locals to req object req.locals = res.locals;

5. Add a req.pushMessage a function to push new messages

// add addMessage function to req object req.pushMessage = addMessage;

function addMessage(message) { // PUSH NEW MESSAGE this.session.messages.push(message); }

6. Add a req.setMessages a function to set the messages array to res.locals.messages and clear the messages array

// add setMessages function to req object req.setMessages = setMessages;

function setMessages() { // ADD MESSAGES TO LOCALS this.locals.messages = this.session.messages; // CLEAR THE MESSAGES ARRAY this.session.messages = []; }

7. Call the next middleware

// call next middleware next();

4. Add the middleware to app

Now, we are going to implement what we have done, into our express app.

Require the middleware at the top of the index.js file:

var flushSystem = require("./flushSystem.js");

Our middleware depends on sessions, for that reason we have to add it after the initialization of the sessions

// sessions app.use( session({ secret: "132c4a71b767b874948afbd00fe1085c", resave: false, saveUninitialized: true, cookie: { secure: false }, }) ); // add flushSystem as middleware app.use(flushSystem());

Now that we have added the middleware, incoming requests objects will always have req.setMessage() and req.setMessages() functions and from the rendering views, we can access the messages array.

At views/template/messages.ejs file we can see how to access the messages array and render flush messages.

views/template/messages.ejs

Our views/home.ejs file has already included messages.ejs

views/home.ejs

Lastly, we have to add some functionality to our app to send messages.

Replace the get method with :

app.get("/", function (req, res) { // set flush messages to render on view req.setMessages(); res.render("pages/home"); });

And add a post method:

app.post("/", function (req, res) { let message = req.body.message; if (message.trim() != "") { req.pushMessage(req.body.message); } res.redirect("/"); });

Start the app:

npm run start

Hit at the browser http://localhost:3000

5. Conclusion

This was a simple flush messaging middleware that you can build super easy and use it if you like at your apps.

You can download the project repository from