👉 Articles tagged : express

Express-session and the redirect() function

Posted on: 2017-06-25

If you are using express-session in your express app, you might have wanted to use the res.redirect() function, and you may have faced an unexpected behaviour : changes on session data are not always saved when the client receives the redirect response from the server and makes a new request to the server.

Here is a solution to always save the session before sending a redirect response : create a middleware that overide the redirect function.

app.use((req, res, next) => {
  const oldRedirect = res.redirect;
  res.redirect = function (...args) {
    if (req.session) {
      // redirecting after saving... => Reflect.apply(oldRedirect, this, args))
    } else {
      Reflect.apply(oldRedirect, this, args);

As you can see ES6 make it simpler ! 😗

Express JS error handling 🌩

Posted on: 2017-05-08

One of the first difficulties you can encounter when you start using Express, is how to handle errors well, especialy if you're using promises.

Here is one way to go. To understand it, remember that in Express, call the next function with an argument (next(new Error('Details about my error')) for example). When you do this, the next middleware capale of handling that argument will be used.

const express = require(`express`);
const app = express();

app.use(`/`, (req, res, next) => {
  return Promise.reject(`something went wrong`)
  .then(() => {
    // of course this wont happen
    // ...

app.use((req, res, next) => {
  // this middleware won't be called
  res.send(`Everything is fine`);

app.use((err, req, res, next) => {
  res.status(500).send(`Your request could not be processed`);

app.listen(3000, () => {
  console.log(`Example app listening on port 3000!`);

Browsing http://localhost:3000/, we'll just see the message : Your request could not be processed.