Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics Middleware Error Handling Middleware

Shehan Dissanayake
Shehan Dissanayake
19,119 Points

res.locals

What actually res.locals do?

I found this is the docs

+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). Otherwise, this property is identical to app.locals.

but im unable to understand it. Can someone explain? Please. Thanks

1 Answer

Boon Kiat Seah
Boon Kiat Seah
66,664 Points

Hi Shehan,

You are passing the error object into the pug template to be rendered on the error.pug template file in this case. The code block below was used by Andrew.

app.use((err, req, res, next) => {
    res.locals.error = err;
    res.status(err.status);
    res.render('error');
});

Another way Andrew taught which i am more familiar with is this code block below. However, both shared the same purpose of passing the object as a js object to be rendered by the pug template to display on the frontend.

app.use((err, req, res, next) => {
    res.status(err.status);
    res.render('error', { error: err });
});

Check this url for more info on how variables are passed into the template if the above is still isn't clear for you.

Hope this helps. Have the best day ever.

regards,

BK