0
0
ExpressHow-ToBeginner · 3 min read

How to Set Views Directory in Express: Simple Guide

In Express, set the views directory using app.set('views', path_to_views). This tells Express where to find your template files for rendering with res.render().
📐

Syntax

The syntax to set the views directory in Express is:

  • app.set('views', directoryPath): Sets the folder where Express looks for template files.
  • directoryPath: A string path to your views folder, usually an absolute path.
javascript
app.set('views', '/path/to/views');
💻

Example

This example shows how to set the views directory to a folder named views inside your project and render an index template.

javascript
import express from 'express';
import path from 'path';

const app = express();

// Set views directory to './views'
app.set('views', path.join(process.cwd(), 'views'));

// Set view engine to e.g. Pug
app.set('view engine', 'pug');

app.get('/', (req, res) => {
  res.render('index', { title: 'Home Page' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when setting the views directory include:

  • Using a relative path without path.join or path.resolve, which can cause Express to look in the wrong folder.
  • Not setting the views directory at all, so Express defaults to ./views relative to where you run the app.
  • Forgetting to set the view engine, which is required to render templates.
javascript
/* Wrong: relative path without path.join */
app.set('views', './views');

/* Right: use path.join for absolute path */
import path from 'path';
app.set('views', path.join(process.cwd(), 'views'));
📊

Quick Reference

Tips for setting views directory in Express:

  • Always use path.join or path.resolve to create an absolute path.
  • Set the view engine with app.set('view engine', 'engineName') after setting views.
  • Default views folder is ./views if not set.

Key Takeaways

Use app.set('views', path) to tell Express where your templates live.
Always provide an absolute path using path.join or path.resolve.
Set the view engine to enable template rendering.
If not set, Express looks for views in the default './views' folder.
Avoid relative paths alone to prevent errors in locating templates.