Express res.render() Method
What you’ll learn
- How to render templates with
res.render(). - How to pass dynamic data to views.
- How to use
res.localsand per-render locals together. - How callback mode works for manual error handling/output control.
Syntax
javascript
res.render(view [, locals] [, callback])1
Render a page with local data
javascript
app.get('/profile', function (req, res) {
res.render('profile', { name: 'Mari', role: 'Admin' });
});2
Combine res.locals and render locals
javascript
app.use(function (req, res, next) {
res.locals.siteName = 'CodeToFun';
next();
});
app.get('/home', function (req, res) {
res.render('home', { pageTitle: 'Welcome' });
});3
Use callback mode for manual handling
javascript
app.get('/preview', function (req, res) {
res.render('preview', { draft: true }, function (err, html) {
if (err) return res.status(500).send('Render error');
res.send(html);
});
});⚠️ Common pitfalls
- Ensure your view engine and views path are configured before calling
res.render(). - Return after handling callback errors to avoid double responses.
- Do not pass untrusted raw HTML unless the template intentionally handles it safely.
❓ FAQ
It renders a view template with provided locals and sends the resulting HTML.
Yes, configure one (for example EJS, Pug, or Handlebars) using app.set('view engine', ...).
Yes, pass an object as the second argument to make values available in the view.
res.render() processes a template file first, while res.send() sends content directly.
Yes, callback mode lets you inspect rendered HTML before sending or handle rendering errors manually.
Did you know?
res.render() compiles a server-side template with data and sends the generated HTML response.
4 people found this page helpful
