Error Handling Middleware

Make sure that the CSRF Token code is on the top of the other Universal code such as the error 500 page, 400 error page or the session User code.

Inside a Async code snipper you need to use next wrapping that error, outside.

You should avoid infinite loops triggered through the error handling middleware as we had it initially here in this code

app.use((error, req, res, next) => { // res.redirect('/500'); res.status(500).render('500', { pageTitle: 'Error', path: '/500', isAuthenticated: req.session.isLoggedIn });


We can throw the error in synchronous code places like this one but inside of promise, then or catch blocks or inside of callbacks, you have to use next around the error.

Like: This is the User Code in our Application

app.use((req, res, next) => { if (!req.session.user) { return next(); } User.findById(req.session.user._id) .then(user => { if (!user) { return next(); } req.user = user; next(); }) .catch(err => { next(new Error(err)) }); });

CSRF Token code looks like this

app.use((req, res, next) => { res.locals.isAuthenticated = req.session.isLoggedIn; res.locals.csrfToken = req.csrfToken(); next(); });

Check the blog for more information about the CSRF Token

0 views0 comments

Recent Posts

See All

SQL UNION Operator UNION operator is used to combine the results of two or more SELECT statements Every SELECT statement within UNION must have the same number of columns The columns must also have si

JOIN clause is used to combine rows from two or more tables. INNER JOIN === selects records that have matching values in both tables SELECT Orders.OrderID, Customers.CustomersID, Orders.OrdersDate FRO