Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn off Node.js Express (ejs template engine) errors for production?

When I'm on a development server and there is an error, Express sends the traceback as a response.

However, this is not good for production. I don't want anyone seeing my trackback.

How can I turn this off?

Note: I'm using EJS as a template engine - this may be the cause, and not express. When I have an undefined variable in the ejs template, for example, ejs renders the traceback and displays it to the user on a white page.

like image 628
TIMEX Avatar asked Aug 17 '14 21:08

TIMEX


People also ask

How to use EJS as a templating engine in Node JS?

To begin with, using EJS as templating engine we need to install EJS using given command: Note: npm in the above commands stands for the node package manager, a place where install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies.

How do I use Express and EJS in NPM?

First, open your terminal window and create a new project directory: Then, navigate to the newly created directory: At this point, you can initialize a new npm project: Next, you will need to install the express package: Then install the ejs package: At this point, you have a new project ready to use Express and EJS.

What is an embedded JavaScript template for node?

When quickly creating Node applications, a fast way to template your application is sometimes necessary. Jade comes as the default template engine for Express but Jade syntax can be overly complex for many use cases. Embedded JavaScript templates (EJS) can be used as an alternative template engine.

What is embedded JavaScript (EJS)?

Embedded JavaScript templates (EJS) can be used as an alternative template engine. In this article, you will learn how to apply EJS to an Express application, include repeatable parts of your site, and pass data to the views. If you would like to follow along with this article, you will need:


1 Answers

The latest version of Express use smart default error handler.

In development mode it sends full stack trace back to the browser, while in production mode it sends only 500 Internal Server Error.

To take advantage of it you should set proper NODE_ENV before running your application.

For example, to run your app in production mode:

NODE_ENV=production node application.js

But if you don't like this default behavior, you could define your own error handler:

app.use(function(err, req, res, next){
  console.error(err);
  res.status(500);
  res.render('error');
});

Note that error handler must be the last middleware in chain, so it should be defined in the bottom of your application.js file.


If you need more information, see:

  • Express official documentation
  • Blog post about error handling in Express
like image 115
Leonid Beschastny Avatar answered Sep 21 '22 12:09

Leonid Beschastny